float compare(const Template &a, const Template &b) const { if (a.size() != distances.size() || b.size() != distances.size()) return -std::numeric_limits<float>::max(); QList<float> scores; for (int i=0; i<distances.size(); i++) { float weight; weights.isEmpty() ? weight = 1. : weight = weights[i]; if (weight != 0) scores.append(weight*distances[i]->compare(Template(a.file, a[i]),Template(b.file, b[i]))); } switch (operation) { case Mean: return std::accumulate(scores.begin(),scores.end(),0.0)/(float)scores.size(); break; case Sum: return std::accumulate(scores.begin(),scores.end(),0.0); break; case Min: return *std::min_element(scores.begin(),scores.end()); break; case Max: return *std::max_element(scores.begin(),scores.end()); break; default: qFatal("Invalid operation."); } return 0; }
int main(int argc, char* argv[]) { if (argc<=1) return ShowHelp(); // run if (GML::Utils::GString::Equals(argv[1],"run",true)) { if (argc!=3) return Error("run command requare a parameter (a template file)"); return Run(argv[2]); } // info if (GML::Utils::GString::Equals(argv[1],"info",true)) { if (argc!=3) return Error("info command requare a parameter (a name for a an Algorithm, Conector, DataBase or Notifier)"); return Info(argv[2]); } // desc if (GML::Utils::GString::Equals(argv[1],"desc",true)) { if (argc!=4) return Error("desc command requare two parameters (a name for a an Algorithm, Conector, DataBase or Notifier and a property)"); return Desc(argv[2],argv[3]); } // template if (GML::Utils::GString::Equals(argv[1],"template",true)) { if ((argc!=4) && (argc!=3)) return Error("template command requares a name for a an Algorithm, Conector, DataBase or Notifier"); if (argc==3) return Template(argv[2],NULL); else return Template(argv[2],argv[3]); } // pytemplate if (GML::Utils::GString::Equals(argv[1],"pytemplate",true)) { if (argc!=3) return Error("pytemplate command requares one parameter (a name for a an Algorithm, Conector, DataBase or Notifier)"); return PyTemplate(argv[2]); } // algorithms if (GML::Utils::GString::Equals(argv[1],"algorithms",true)) return ShowObjects(ALGORITHM_FOLDER,ALGORITHM_EXT); // connectors if (GML::Utils::GString::Equals(argv[1],"connectors",true)) return ShowObjects(CONNECTOR_FOLDER,CONNECTOR_EXT); // notifiers if (GML::Utils::GString::Equals(argv[1],"notifiers",true)) return ShowObjects(NOTIFYER_FOLDER,NOTIFYER_EXT); // databases if (GML::Utils::GString::Equals(argv[1],"databases",true)) return ShowObjects(DATABASE_FOLDER,DATABASE_EXT); printf("[ERROR] Unknwon command : %s \n",argv[1]); return -1; }
//CImg* Template(int nTempH, int nTempW, int nTempMY, int nTempMX,double *pfArray, double fCoef,CImg *pImg); CImg* CDimageView::Sobel(CImg *pImg) { CImg* mImg1= new CImg(*pImg); CImg* mImg2= new CImg(*pImg); int width=pImg->GetWidthPixel(); int height=pImg->GetHeight(); mImg1 = Template(3, 3, 1, 1, Template_HSobel, 1, pImg); mImg2 = Template(3, 3, 1, 1, Template_VSobel, 1, pImg); //CImg* mImg = new CImg((*mImg1)+(*mImg2)); CImg* mImg = new CImg((*mImg1)+(*mImg2)); return mImg; }
CImg* CDimageView::PrewittEdge(CImg* pImg,int index) { double cfPrewittH[9] = { -1, -2, -1, 0, 0, 0, 1, 2, 1 }; // 垂直边缘 double cfPrewittV[9] = { -1, 0, 1, -2, 0, 2, -1, 0, 1 }; // 45度边缘 double cfPrewittCW[9] = { -2, -1, 0, -1, 0, 1, 0, 1, 2 }; // 135度边缘 double cfPrewittCCW[9] = { 0, 1, 2, -1, 0, 1, -2, -1, 0 }; CImg* mImg1= new CImg(*pImg); CImg* mImg2= new CImg(*pImg); CImg* mImg3= new CImg(*pImg); CImg* mImg4= new CImg(*pImg); int width=pImg->GetWidthPixel(); int height=pImg->GetHeight(); mImg1 = Template(3, 3, 1, 1, cfPrewittH, 1, pImg); mImg2 = Template(3, 3, 1, 1, cfPrewittV, 1, pImg); mImg3 = Template(3, 3, 1, 1, cfPrewittCW, 1, pImg); mImg4 = Template(3, 3, 1, 1, cfPrewittCCW, 1, pImg); CImg* nImg = new CImg((*mImg1)+(*mImg2)+(*mImg3)+(*mImg4)); // CImg* mImg = new CImg((*mImg2)); CImg* mImg= Autothres (nImg); switch(index) { case 0:return mImg; case 1:return Autothres (mImg1); case 2:return Autothres (mImg2); case 3:return Autothres (mImg3); case 4:return Autothres (mImg4); } }
extern "C" __declspec(dllexport) void CBMENUENTRY(CBTYPE cbType, PLUG_CB_MENUENTRY* info) { switch(info->hEntry) { case MENU_TEMPLATE: // edit this Template(); break; } }
void CDimageView::OnenSmoothf() { // TODO: 在此添加命令处理程序代码 CDimageDoc* pDoc= GetDocument(); if(!pDoc->m_Img->IsValidate()) return; if(pDoc->m_OImg->IsValidate()) { delete []pDoc->m_OImg; pDoc->m_OImg=NULL; } pDoc->m_OImg= new CImg(*pDoc->m_Img); int nTempH; // 模板高度 int nTempW; // 模板宽度 double fTempC;// 模板系数 int nTempMX;// 模板中心元素X坐标 int nTempMY;// 模板中心元素Y坐标 // 模板元素数组赋初值(默认为平均模板) double aValue[9] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,}; // 创建对话框 DlgSmooth dlg; // 初始化对话框变量值 dlg.m_intType = 0; dlg.m_iTempH = 3; dlg.m_iTempW = 3; dlg.m_iTempMX = 1; dlg.m_iTempMY = 1; dlg.m_fTempC = (double) (1.0 / 9.0); dlg.m_fpArray = aValue; // 显示对话框,提示用户设定参数 if (dlg.DoModal() != IDOK) { // 返回 return; } // 获取用户设定的参数 nTempH = dlg.m_iTempH; nTempW = dlg.m_iTempW; nTempMX = dlg.m_iTempMX; nTempMY = dlg.m_iTempMY; fTempC = dlg.m_fTempC; delete []pDoc->m_Img; pDoc->m_Img = Template(nTempH, nTempW, nTempMY, nTempMX, aValue, fTempC, pDoc->m_OImg); Invalidate(1); }
CImg* CDimageView::SobelEdge(CImg* pImg) { double cfSobelH[9] = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }; // 垂直边缘 double cfSobelV[9] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; // 45度边缘 double cfSobelCW[9] = { -1, -1, 0, -1, 0, 1, 0, 1, 1 }; // 135度边缘 double cfSobelCCW[9] = { 0, 1, 1, -1, 0, 1, -1, -1, 0 }; CImg* mImg1= new CImg(*pImg); CImg* mImg2= new CImg(*pImg); CImg* mImg3= new CImg(*pImg); CImg* mImg4= new CImg(*pImg); int width=pImg->GetWidthPixel(); int height=pImg->GetHeight(); mImg1 = Template(3, 3, 1, 1, cfSobelH, 1, pImg); mImg2 = Template(3, 3, 1, 1, cfSobelV, 1, pImg); mImg3 = Template(3, 3, 1, 1, cfSobelCW, 1, pImg); mImg4 = Template(3, 3, 1, 1, cfSobelCCW, 1, pImg); CImg* nImg = new CImg((*mImg1)+(*mImg2)+(*mImg3)+(*mImg4)); // CImg* nImg = new CImg((*mImg1)+(*mImg2)); // CImg* mImg = new CImg((*mImg2)); CImg* mImg= Autothres (nImg); return mImg; }
CImg* CDimageView::RobertEdge(CImg* pImg) { double cfRobertCW[4]={-1 , 0, 0 , 1}; double cfRobertCCW[4]={0 , -1, 1 , 0}; CImg* mImg1= new CImg(*pImg); CImg* mImg2= new CImg(*pImg); int width=pImg->GetWidthPixel(); int height=pImg->GetHeight(); mImg1 = Template(2, 2, 0, 0, cfRobertCW, 1, pImg); mImg2 = Template(2, 2, 0, 0, cfRobertCCW, 1, pImg); CImg* nImg = new CImg((*mImg1)+(*mImg2)); // CImg* mImg = new CImg((*mImg2)); CImg* mImg= Autothres (nImg); return mImg; }
// Return false if the entity is to be destroyed bool CAmmoEntity::Update(TFloat32 updateTime) { if (!landed) { Position().y -= m_FallSpeed * updateTime; if (Position().y < m_Height) { landed = true; } } else { m_SinWave += updateTime; Position().y = m_Height + sin(m_SinWave); // Rotate on the spot and bob up and down (for effect) Matrix().RotateY((kfPi / 3) * updateTime); } //TODO: Collision detection TInt32 enumID; EntityManager.BeginEnumEntities(enumID, "", "", "Tank"); CTankEntity* theTank = dynamic_cast<CTankEntity*> (EntityManager.EnumEntity(enumID)); while (theTank) { float radius = Template()->Mesh()->BoundingRadius(); if (Length(Position() - theTank->Position()) < (theTank->GetRadius() + radius)) //If distance between the ammo and the tank is less than the tank's radius { EntityManager.EndEnumEntities(enumID); // Hit the tank, send the hit message and destroy the bullet SMessage theCollectMessage; theCollectMessage.from = GetUID(); theCollectMessage.type = Msg_Ammo; theCollectMessage.intParam = m_RefillSize; Messenger.SendMessageA(theTank->GetUID(), theCollectMessage); return false; } theTank = dynamic_cast<CTankEntity*> (EntityManager.EnumEntity(enumID)); } EntityManager.EndEnumEntities(enumID); return true; }
NQInt NQInt::operator*(NQInt A) {//ЭТО УМНОЖЕНИЕ! NQList<int> Resulted; int incr = 0; for (int i = -underValueLeng; i < valueLeng; i++) for (int j = -A.underValueLeng; j < A.valueLeng; j++) {//идем с двух сторон unsigned long long Value; if (i >= -underValueLeng && i < valueLeng && j >= -A.underValueLeng && j < A.valueLeng)//проверка была не знаю зачем - удалить! { Value =((unsigned long long)THIS[i])*(unsigned long long)A[j] +(unsigned long long)incr; //берется произведение, высчитывается инкремент следующих разрядов incr = Value / Notation; Value -= ((unsigned long long)incr)*((unsigned long long)Notation);//Сокращение длины if (i+j + underValueLeng + A.underValueLeng >= Resulted.Count()) Resulted.addLast(Value);//добавление нового если необходимо else {//морока с разрядами =) unsigned long long Val = (unsigned long long)Resulted[i+j+underValueLeng+A.underValueLeng] + Value; int Dincr = Val / Notation; Val -= ((unsigned long long)Dincr)*((unsigned long long)Notation); Resulted[i+j+underValueLeng+A.underValueLeng] = Val; incr += Dincr; } if (incr) if (i+j + underValueLeng + A.underValueLeng+1 >= Resulted.Count()) Resulted.addLast(incr); else {//перевод разрядов Resulted[i+j+underValueLeng+A.underValueLeng + 1] += incr; } incr = 0; for (int k = i+j+underValueLeng+A.underValueLeng; k < Resulted.Count()-1 && Resulted[k] >= Notation; k++) { int D = Resulted[k] / Notation; Resulted[k] -= D*Notation; Resulted[k+1] += D; } } } NQInt Template(underValueLeng+A.underValueLeng,((A.Positive && Positive)||(!A.Positive && !Positive)),Resulted); return Template; }
//Разница чисел NQInt NQInt::operator-(NQInt A) {//Разность //переход с одной функции на другую if (Positive && !A.Positive) { A.Positive = true; return THIS + A; } if (!Positive && A.Positive) { A.Positive = false; return THIS + A; } int max = valueLeng> A.valueLeng?valueLeng:A.valueLeng;//положительная максимальня int min = underValueLeng>A.underValueLeng?underValueLeng:A.underValueLeng;//минимальная максимальная отрицательная NQList<int> Resulted;//накопитель int incr = 0; int CompareResult = Compare(A); if (CompareResult) for (int i =-min; i<max; i++) {//подсчет разницы, с переносом инкриментов long long Value = 0; if (i >= -underValueLeng && i<valueLeng) Value += THIS[i]*(CompareResult); if (i >= -A.underValueLeng && i<A.valueLeng) Value -= A[i]*(CompareResult); Value += incr; incr = 0; if (Value < 0) { Value = Notation + Value; incr = -1; } Resulted.addLast(Value); } else {//Если числа равны? char *Temp = new char[2]; Temp[0] = '0'; Temp[1] = 0; return Temp; } NQInt Template(min,(CompareResult+1),Resulted); return Template; }
void CDlgTemplate::OnRadio8() { // TODO: Add your control notification handler code here aver = (float)(1.0/8.0); int smoothg[9] = {1,1,1,1,0,1,1,1,1}; for(int k=0; k<9; k++) { smooth[k]=smoothg[k]; } if(Tbitmap!=NULL) { DeleteObject(Tbitmap); Tbitmap=NULL; } Tbitmap=Template(m_dib.newpcol,m_dib.newbm,m_dib.NEWRGB32BITMAPINFO); ((CStatic *)GetDlgItem(IDC_STATIC2))->SetBitmap(Tbitmap); }
BOOL CDlgTemplate::OnInitDialog() { CMainDlg::OnInitDialog(); ((CButton *)GetDlgItem(IDC_RADIO4))->SetCheck(1); ((CStatic *)GetDlgItem(IDC_STATIC1))->SetBitmap(m_dib.newbmp); // ((CStatic *)GetDlgItem(IDC_STATIC2))->SetBitmap(m_dib.newbmp); if(Tbitmap!=NULL) { DeleteObject(Tbitmap); Tbitmap=NULL; } Tbitmap=Template(m_dib.newpcol,m_dib.newbm,m_dib.NEWRGB32BITMAPINFO); ((CStatic *)GetDlgItem(IDC_STATIC2))->SetBitmap(Tbitmap); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
void CChildView::OnGass() { // TODO: Add your command handler code here //设定模板参数 double tem[9]={1,2,1, 2,4,2, 1,2,1}; //设定模板系数 double xishu = 0.0625; //进行模板操作 m_hDIB =Template(m_hDIB,tem ,3,3, xishu); //显示图像 CDC* pDC=GetDC(); DisplayDIB(pDC,m_hDIB); }
CImg* CDimageView::LogEdge(CImg* pImg) { double cfLog[25]={0, 0, -1, 0, 0, 0, -1, -2, -1, 0, -1, -2, 16, -2, -1, 0, -1, -2, -1, 0, 0, 0, -1, 0, 0}; CImg* mImg1= new CImg(*pImg); int width=pImg->GetWidthPixel(); int height=pImg->GetHeight(); mImg1 = Template(5, 5, 2, 2, cfLog, 1, pImg); // CImg* mImg = new CImg((*mImg2)); CImg* mImg= Autothres (mImg1); return mImg; }
void CDimageView::OnenLapaces() { // TODO: 在此添加命令处理程序代码 CDimageDoc* pDoc= GetDocument(); if(!pDoc->m_Img->IsValidate()) return; if(pDoc->m_OImg->IsValidate()) { delete []pDoc->m_OImg; pDoc->m_OImg=NULL; } pDoc->m_OImg= new CImg(*pDoc->m_Img); int nTempW = 3; int nTempH = 3; double fCoef = 1.0; int nTempMX = 1; int nTempMY = 1; delete []pDoc->m_Img; pDoc->m_Img=Template(nTempH, nTempW, nTempMY, nTempMX, Template_Laplace, fCoef, pDoc->m_OImg); Invalidate(0); }
BOOL CmyWord::CreateDocument() { if (!m_wdDocs.m_lpDispatch) { AfxMessageBox(_T("Documents为空!"), MB_OK|MB_ICONWARNING); return FALSE; } COleVariant varTrue(short(1),VT_BOOL),vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); CComVariant Template(_T("")); //没有使用WORD的文档模板 CComVariant NewTemplate(false),DocumentType(0),Visible; m_wdDocs.Add(&Template,&NewTemplate,&DocumentType,&Visible); //得到document变量 m_wdDoc = m_wdApp.GetActiveDocument(); if (!m_wdDoc.m_lpDispatch) { AfxMessageBox(_T("Document获取失败!"), MB_OK|MB_ICONWARNING); return FALSE; } //得到selection变量 m_wdSel = m_wdApp.GetSelection(); if (!m_wdSel.m_lpDispatch) { AfxMessageBox(_T("Select获取失败!"), MB_OK|MB_ICONWARNING); return FALSE; } //得到Range变量 m_wdRange = m_wdDoc.Range(vOptional,vOptional); if(!m_wdRange.m_lpDispatch) { AfxMessageBox(_T("Range获取失败!"), MB_OK|MB_ICONWARNING); return FALSE; } return TRUE; }
namespace SuperStatsBros { static const unsigned int FRAME_SKIP = 10; static const cv::Size GAME_RES(640, 480); static const double LOCALIZE_THRESHOLD = 0.85; static const double TEMPLATE_CONTOUR_THRESHOLD = 0.55; static const double STOCK_MATCH_THRESHOLD = 0.50; static const LocalizationParams LOCALIZE_CHAR_SELECT(Template("assets/text/back.png", 1.2), cv::Point(520, 17)); static const LocalizationParams LOCALIZE_STAGE_SELECT(Template("assets/text/stage_select.png", 0.9, 0.95), cv::Point(342, 400)); static const LocalizationParams LOCALIZE_IN_GAME(Template("assets/text/ready_italic.png", 0.8), cv::Point(138, 151)); static const LocalizationParams LOCALIZE_PAUSED(Template("assets/text/combo.png", 0.928, 1), cv::Point(461, 397)); static const LocalizationParams LOCALIZE_END_GAME(Template("assets/text/game.png", 0.928, 0.88), cv::Point(89, 149)); static const LocalizationParams LOCALIZE_SCORE_SCREEN(Template("assets/text/winner.png", 0.95, 2), cv::Point(25, 48)); static const double STAGE_NAME_SCALE_X = 0.65; static const double STAGE_NAME_SCALE_Y = 0.73; static const double STAGE_NAME_ROTATION = -10.0; static const unsigned int STOCK_ORIGIN_X[] = { 25, 177, 329, 481 }; static const unsigned int STOCK_ORIGIN_Y = 362; static const cv::Size STOCK_SIZE(26, 23); static const unsigned int NUM_PLAYERS = 4; static const unsigned int MAX_STOCKS = 5; static const unsigned int DMG_THRESHOLD = 200; static const unsigned int MIN_CONFIDENCE = 90; static const unsigned int DMG_ORIGIN_Y = 405; static const cv::Size DMG_SIZE(102, 39); static const double STATE_MISMATCH_DELAY = 0.5; static const double UNPAUSE_SECONDS_DELAY = 1.0; static const double START_GAME_SECONDS_DELAY = 4.0; } /* SuperStatsBros */
void csWrappedDocumentNode::ProcessSingleWrappedNode ( NodeProcessingState* state, iDocumentNode* node) { CS_ASSERT(globalState); if (ProcessTemplate (node, state)) return; if (ProcessStaticIf (state, node)) { // Template invokation has precedence over dropping nodes... TempString<> tokenStr, args; if (SplitNodeValue (node->GetValue(), tokenStr, args)) { Template::Params params; if (!args.IsEmpty()) { ParseTemplateArguments (args, params, false); } InvokeTemplate (tokenStr, node, state, params); } return; } csRefArray<iDocumentNode>& currentWrapper = state->currentWrapper; bool handled = false; if (node->GetType() == CS_NODE_UNKNOWN) { TempString<> replaceScratch; const char* nodeValue = ReplaceEntities (node->GetValue(), replaceScratch); if ((nodeValue != 0) && (*nodeValue == '?') && (*(nodeValue + strlen (nodeValue) - 1) == '?')) { const char* valStart = nodeValue + 1; if ((*valStart == '!') || (*valStart == '#')) { /* Discard PIs beginning with ! and #. This allows comments, e.g. * <?! some comment ?> * The difference to XML comments is that the PI comments do not * appear in the final document after processing, hence are useful * if some PIs themselves are to be commented, but it is undesireable * to have an XML comment in the result. */ return; } while (*valStart == ' ') valStart++; CS_ASSERT (*valStart != 0); size_t valLen = strlen (valStart) - 1; if (valLen == 0) { Report (syntaxErrorSeverity, node, "Empty processing instruction"); } else { while (*(valStart + valLen - 1) == ' ') valLen--; const char* space = strchr (valStart, ' '); /* The rightmost spaces were skipped and don't interest us any more. */ if (space >= valStart + valLen) space = 0; size_t cmdLen; if (space != 0) { cmdLen = space - valStart; } else { cmdLen = valLen; } TempString<> tokenStr; tokenStr.Replace (valStart, cmdLen); csStringID tokenID = shared->pitokens.Request (tokenStr); switch (tokenID) { case csWrappedDocumentNodeFactory::PITOKEN_INCLUDE: if (shared->plugin->do_verbose) { Report (CS_REPORTER_SEVERITY_WARNING, node, "Deprecated syntax, please use %s", CS::Quote::Single ("Include")); } // Fall through case csWrappedDocumentNodeFactory::PITOKEN_INCLUDE_NEW: { bool okay = true; TempString<> filename; const char* space = strchr (valStart, ' '); /* The rightmost spaces were skipped and don't interest us * any more. */ if (space != 0) { filename.Replace (space + 1, valLen - cmdLen - 1); filename.Trim (); } if ((space == 0) || (filename.IsEmpty ())) { Report (syntaxErrorSeverity, node, "%s without filename", CS::Quote::Single ("Include")); okay = false; } if (okay) { ProcessInclude (filename, state, node); } handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_TEMPLATE: if (shared->plugin->do_verbose) { Report (CS_REPORTER_SEVERITY_WARNING, node, "Deprecated syntax, please use %s", CS::Quote::Single ("Template")); } // Fall through case csWrappedDocumentNodeFactory::PITOKEN_TEMPLATE_NEW: case csWrappedDocumentNodeFactory::PITOKEN_TEMPLATEWEAK: { TempString<> args (valStart + cmdLen, valLen - cmdLen); args.LTrim(); ProcessInstrTemplate (state, node, args, tokenID == csWrappedDocumentNodeFactory::PITOKEN_TEMPLATEWEAK); handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_ENDTEMPLATE: if (shared->plugin->do_verbose) { Report (CS_REPORTER_SEVERITY_WARNING, node, "Deprecated syntax, please use %s", CS::Quote::Single ("Endtemplate")); handled = true; } // Fall through case csWrappedDocumentNodeFactory::PITOKEN_ENDTEMPLATE_NEW: { Report (syntaxErrorSeverity, node, "%s without %s", CS::Quote::Single ("Endtemplate"), CS::Quote::Single ("Template")); // ProcessTemplate() would've handled it otherwise handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_GENERATE: { bool okay = true; Template::Params args; if (space != 0) { TempString<> pStr (space + 1, valLen - cmdLen - 1); ParseTemplateArguments (pStr, args, false); } if ((args.GetSize() < 3) || (args.GetSize() > 4)) { okay = false; Report (syntaxErrorSeverity, node, "%s expects 3 or 4 arguments, got %zu", CS::Quote::Single ("Generate"), args.GetSize()); } if (okay) { state->generateVar = args[0]; int start, end, step; char dummy; if (sscanf (args[1], "%d%c", &start, &dummy) != 1) { Report (syntaxErrorSeverity, node, "Argument %s is not an integer", CS::Quote::Single (args[1].GetData())); okay = false; } if (okay && sscanf (args[2], "%d%c", &end, &dummy) != 1) { Report (syntaxErrorSeverity, node, "Argument %s is not an integer", CS::Quote::Single (args[2].GetData())); okay = false; } if (okay) { if (args.GetSize() == 4) { if (sscanf (args[3], "%d%c", &step, &dummy) != 1) { Report (syntaxErrorSeverity, node, "Argument %s is not an integer", CS::Quote::Single (args[3].GetData())); okay = false; } } else { step = (end < start) ? -1 : 1; } } if (okay) { state->generateActive = true; state->generateNestLevel = 1; if (((start > end) && (step >= 0)) || ((end >= start) && (step <= 0))) { Report (syntaxErrorSeverity, node, "Can't reach end value %d starting from %d with step %d", end, start, step); state->generateValid = false; } else { state->generateValid = true; state->generateStart = start; state->generateEnd = end; state->generateStep = step; state->templ = Template(); } } } handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_ENDGENERATE: { Report (syntaxErrorSeverity, node, "%s without %s", CS::Quote::Single ("Endgenerate"), CS::Quote::Single ("Generate")); // ProcessTemplate() would've handled it otherwise } break; case csWrappedDocumentNodeFactory::PITOKEN_DEFINE: { TempString<> args (valStart + cmdLen, valLen - cmdLen); args.LTrim(); ProcessDefine (state, node, args); handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_UNDEF: { TempString<> args (valStart + cmdLen, valLen - cmdLen); args.LTrim(); ProcessUndef (state, node, args); handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_STATIC_IFDEF: case csWrappedDocumentNodeFactory::PITOKEN_STATIC_IFNDEF: { TempString<> args (valStart + cmdLen, valLen - cmdLen); args.LTrim(); ProcessStaticIfDef (state, node, args, tokenID == csWrappedDocumentNodeFactory::PITOKEN_STATIC_IFNDEF); handled = true; } break; case csWrappedDocumentNodeFactory::PITOKEN_STATIC_ELSIFDEF: case csWrappedDocumentNodeFactory::PITOKEN_STATIC_ELSIFNDEF: case csWrappedDocumentNodeFactory::PITOKEN_STATIC_ELSE: case csWrappedDocumentNodeFactory::PITOKEN_STATIC_ENDIF: { Report (syntaxErrorSeverity, node, "%s without %s", CS::Quote::Single (shared->pitokens.Request (tokenID)), CS::Quote::Single ("SIfDef")); // ProcessStaticIf() would've handled it otherwise handled = true; } break; default: { Template::Params params; if (space != 0) { TempString<> pStr (space + 1, valLen - cmdLen - 1); ParseTemplateArguments (pStr, params, false); } if (InvokeTemplate (tokenStr, node, state, params)) { handled = true; } // If it's neither a template nor a recognized command, pass through } } } } } if (!handled) { csRef<iDocumentNode> newWrapper; newWrapper.AttachNew (new csWrappedDocumentNode (this, node, shared, globalState)); currentWrapper.Push (newWrapper); } }
void DtwPsClassifier::addTemplate() { templateBank.push_back(Template()); }
void compare(File targetGallery, File queryGallery, File output) { qDebug("Comparing %s and %s%s", qPrintable(targetGallery.flat()), qPrintable(queryGallery.flat()), output.isNull() ? "" : qPrintable(" to " + output.flat())); // Escape hatch for distances that need to operate directly on the gallery files if (distance->compare(targetGallery, queryGallery, output)) return; // Are we comparing the same gallery against itself? bool selfCompare = targetGallery == queryGallery; // Should we use multiple processes to do enrollment/comparison? If not, we just do multi-threading. bool multiProcess = Globals->file.getBool("multiProcess", false); // In comparing two galleries, we will keep the smaller one in memory, and load the larger one // incrementally. If the gallery set is larger than the probe set, we operate in transpose mode // i.e. we must transpose our output, to still write the output matrix in row-major order. bool transposeMode = false; // Is the larger gallery already enrolled? If not, we will enroll those images in-line with their // comparison against the smaller gallery (which will be enrolled, and stored in memory). bool needEnrollRows = false; if (output.exists() && output.get<bool>("cache", false)) return; if (queryGallery == ".") queryGallery = targetGallery; // To decide which gallery is larger, we need to read both, but at this point we just want the // metadata, and don't need the enrolled matrices. FileList targetMetadata; FileList queryMetadata; // Emptyread reads a gallery, and discards any matrices present, keeping only the metadata. targetMetadata = FileList::fromGallery(targetGallery, true); queryMetadata = FileList::fromGallery(queryGallery, true); // Is the target or query set larger? We will use the larger as the rows of our comparison matrix (and transpose the output if necessary) transposeMode = targetMetadata.size() > queryMetadata.size(); File rowGallery = queryGallery; File colGallery = targetGallery; qint64 rowSize; Gallery * temp; if (transposeMode) { rowGallery = targetGallery; colGallery = queryGallery; temp = Gallery::make(targetGallery); } else { temp = Gallery::make(queryGallery); } rowSize = temp->totalSize(); delete temp; // Is the column gallery already enrolled? We keep the enrolled column gallery in memory, and in multi-process // mode, every worker process retains a copy of this gallery in memory. When not in multi-process mode, we can // simple make sure the enrolled data is stored in a memGallery, but in multi-process mode we save the enrolled // data to disk (as a .gal file) so that each worker process can read it without re-doing enrollment. File colEnrolledGallery = colGallery; QString targetExtension = multiProcess ? "gal" : "mem"; // If the column gallery is not already of the appropriate type, we need to do something if (colGallery.suffix() != targetExtension) { // Build the name of a gallery containing the enrolled data, of the appropriate type. colEnrolledGallery = colGallery.baseName() + colGallery.hash() + (multiProcess ? ".gal" : ".mem"); // Check if we have to do real enrollment, and not just convert the gallery's type. if (!(QStringList() << "gal" << "template" << "mem").contains(colGallery.suffix())) { enroll(colGallery, colEnrolledGallery); } // If the gallery does have enrolled templates, but is not the right type, we do a simple // type conversion for it. else { QScopedPointer<Gallery> readColGallery(Gallery::make(colGallery)); TemplateList templates = readColGallery->read(); QScopedPointer<Gallery> enrolledColOutput(Gallery::make(colEnrolledGallery)); enrolledColOutput->writeBlock(templates); } } // We have handled the column gallery, now decide whehter or not we have to enroll the row gallery. if (selfCompare) { // For self-comparisons, we just use the already enrolled column set. rowGallery = colEnrolledGallery; } // Otherwise, we will need to enroll the row set. Since the actual comparison is defined via a transform // which compares incoming templates against a gallery, we will handle enrollment of the row set by simply // building a transform that does enrollment (using the current algorithm), then does the comparison in one // step. This way, we don't have to retain the complete enrolled row gallery in memory, or on disk. else if(!(QStringList() << "gal" << "mem" << "template").contains(rowGallery.suffix())) { needEnrollRows = true; } // At this point, we have decided how we will structure the comparison (either in transpose mode, or not), // and have the column gallery enrolled, and have decided whether or not we need to enroll the row gallery. // From this point, we will build a single algorithm that (optionally) does enrollment, then does comparisons // and output, optionally using ProcessWrapper to do the enrollment and comparison in separate processes. // // There are two main components to this algorithm. The first is the (optional) enrollment and then the // comparison step (built from a GalleryCompare transform), and the second is the sequential matrix output and // progress counting step. // After the base algorithm is built, the whole thing will be run in a stream, so that I/O can be handled sequentially. // The actual comparison step is done by a GalleryCompare transform, which has a Distance, and a gallery as data. // Incoming templates are compared against the templates in the gallery, and the output is the resulting score // vector. QString compareRegionDesc = "Pipe([GalleryCompare("+Globals->algorithm + "," + colEnrolledGallery.flat() + ")])"; QScopedPointer<Transform> compareRegion; // If we need to enroll the row set, we add the current algorithm's enrollment transform before the // GalleryCompare in a pipe. if (needEnrollRows) { if (!multiProcess) { compareRegionDesc = compareRegionDesc; compareRegion.reset(Transform::make(compareRegionDesc,NULL)); CompositeTransform * downcast = dynamic_cast<CompositeTransform *> (compareRegion.data()); if (downcast == NULL) qFatal("Pipe downcast failed in compare"); downcast->transforms.prepend(this->transform.data()); downcast->init(); } else { compareRegionDesc = "ProcessWrapper(" + this->transformString + "+" + compareRegionDesc + ")"; compareRegion.reset(Transform::make(compareRegionDesc, NULL)); } } else { if (multiProcess) compareRegionDesc = "ProcessWrapper(" + compareRegionDesc + ")"; compareRegion.reset(Transform::make(compareRegionDesc,NULL)); } // At this point, compareRegion is a transform, which optionally does enrollment, then compares the row // set against the column set. If in multi-process mode, the enrollment and comparison are wrapped in a // ProcessWrapper transform, and will be transparently run in multiple processes. compareRegion->init(); // We also need to add Output and progress counting to the algorithm we are building, so we will assign them to // two stages of a pipe. QString joinDesc = "Pipe()"; QScopedPointer<Transform> join(Transform::make(joinDesc, NULL)); // The output transform takes the metadata memGalleries we set up previously as input, along with the // output specification we were passed. Gallery metadata is necessary for some Outputs to function correctly. QString outputString = output.flat().isEmpty() ? "Empty" : output.flat(); QString outputRegionDesc = "Output("+ outputString +"," + targetGallery.flat() +"," + queryGallery.flat() + ","+ QString::number(transposeMode ? 1 : 0) + ")"; // The ProgressCounter transform will simply provide a display about the number of rows completed. outputRegionDesc += "+ProgressCounter("+QString::number(rowSize)+")+Discard"; QScopedPointer<Transform> outputTform(Transform::make(outputRegionDesc, NULL)); // Assign the comparison transform we previously built, and the output transform we just built to // two stages of a pipe. CompositeTransform * downcast = dynamic_cast<CompositeTransform *> (join.data()); downcast->transforms.append(compareRegion.data()); downcast->transforms.append(outputTform.data()); // With this, we have set up a transform which (optionally) enrolls templates, compares them // against a gallery, and outputs them. join->init(); // Now, we will give that base transform to a stream, which will incrementally read the row gallery // and pass the transforms it reads through the base algorithm. QString streamDesc = "Stream(readMode=StreamGallery)"; QScopedPointer<Transform> streamBase(Transform::make(streamDesc, NULL)); WrapperTransform * streamWrapper = dynamic_cast<WrapperTransform *> (streamBase.data()); streamWrapper->transform = join.data(); // The transform we will use is now complete. streamWrapper->init(); // We set up a template containing the rowGallery we want to compare. TemplateList rowGalleryTemplate; rowGalleryTemplate.append(Template(rowGallery)); TemplateList outputGallery; // Set up progress counting variables Globals->currentStep = 0; Globals->totalSteps = rowSize; Globals->startTime.start(); // Do the actual comparisons streamWrapper->projectUpdate(rowGalleryTemplate, outputGallery); }
static Template parse(const dotX39::Node& node, const std::vector<Ressource>& ressourceList) { auto tmp = Template(); tmp.qualifier = node.getName(); #pragma region Argument Parsing for (int i = 0; i < node.getArgumentCount(); i++) { const dotX39::Data* arg = node.getArgument(i); if (arg->getName().compare("path") == 0) { if (arg->getType() != dotX39::DataTypes::STRING) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' 'path' argument should be STRING") << std::endl; throw Exceptions::InvalidTypeStructureException(); } tmp.filePath = std::string(Globals::getInstance().basePath.templates).append(static_cast<const dotX39::DataString*>(arg)->getDataAsString()); } else if (arg->getName().compare("fileName") == 0) { if (arg->getType() != dotX39::DataTypes::STRING) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' 'fileName' argument should be STRING") << std::endl; throw Exceptions::InvalidTypeStructureException(); } tmp.outputFileName = std::string(static_cast<const dotX39::DataString*>(arg)->getDataAsString()); } else if (arg->getName().compare("fileExtension") == 0) { if (arg->getType() != dotX39::DataTypes::STRING) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' 'fileExtension' argument should be STRING") << std::endl; throw Exceptions::InvalidTypeStructureException(); } tmp.outputFileExtension = std::string(static_cast<const dotX39::DataString*>(arg)->getDataAsString()); } else { if (Globals::getInstance().verbosity) std::cout << std::string("the node '").append(tmp.qualifier).append("' contains the unknown argument '").append(arg->getName()).append("', ignored.") << std::endl; } } #pragma endregion #pragma region Data Parsing for (int i = 0; i < node.getDataCount(); i++) { const dotX39::Data* data = node.getData(i); if (data->getName().compare("ressources") == 0) { if (data->getType() != dotX39::DataTypes::ARRAY) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' 'ressources' argument should be ARRAY") << std::endl; throw Exceptions::InvalidTypeStructureException(); } auto tmpDataArray = static_cast<const dotX39::DataArray*>(data); //We want to validate ALL ressources here so lets create an error counter instead of throwing an exception instantly size_t errCount = 0; for (int j = 0; j < tmpDataArray->getDataCount(); j++) { auto data = tmpDataArray->getDataElement(j); if (data->getType() != dotX39::DataTypes::STRING) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' 'ressource' argument should be ARRAY with just STRINGs") << std::endl; throw Exceptions::InvalidTypeStructureException(); } //Find the ressource in available ressources and push it to the templates ressource list bool flag = false; auto ressourceName = static_cast<const dotX39::DataString*>(data)->getDataAsString(); for (auto& it : ressourceList) { if (it.getQualifier().compare(ressourceName) == 0) { tmp.ressources.push_back(it); flag = true; break; } } if (!flag) { errCount++; std::cerr << "Ressource '" << ressourceName << "' is not existing (template: '" << tmp.qualifier << "')" << std::endl; } } //if we did found errors, throw the invalid_argument exception if (errCount > 0) throw std::invalid_argument("Some Ressources are not existing for a Template"); } else { if (Globals::getInstance().verbosity) std::cout << std::string("the node '").append(tmp.qualifier).append("' contains the unknown argument '").append(data->getName()).append("', ignored.") << std::endl; } } #pragma endregion #pragma region Node Parsing for (int i = 0; i < node.getNodeCount(); i++) { auto subnode = node.getNode(i); if (subnode->getName().compare("templateKeywords") == 0) { for (int j = 0; j < subnode->getDataCount(); j++) { auto data = subnode->getData(j); if (data->getType() != dotX39::DataTypes::STRING) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' subnodes '").append(subnode->getName()).append("' data datatypes should be STRING") << std::endl; throw Exceptions::InvalidTypeStructureException(); } auto templateKeyword = TemplateKeyword::parse(*static_cast<const dotX39::DataString*>(data)); tmp.keywords.templates.push_back(templateKeyword); } } else if (subnode->getName().compare("replacementKeywords") == 0) { for (int j = 0; j < subnode->getDataCount(); j++) { auto data = subnode->getData(j); if (data->getType() != dotX39::DataTypes::ARRAY) { std::cerr << std::string("the nodes '").append(tmp.qualifier).append("' subnodes '").append(subnode->getName()).append("' data datatypes should be ARRAY") << std::endl; throw Exceptions::InvalidTypeStructureException(); } tmp.keywords.replacements.push_back(ReplacementKeyword::parse(*static_cast<const dotX39::DataArray*>(data))); } } else { if (Globals::getInstance().verbosity) std::cout << std::string("the node '").append(tmp.qualifier).append("' contains the unknown node '").append(subnode->getName()).append("', ignored.") << std::endl; } } #pragma endregion if (tmp.filePath.empty()) { std::cerr << std::string("the node '").append(tmp.getQualifier()).append("' has no path argument provided") << std::endl; exit(-1); } std::ifstream stream = std::ifstream(std::string(tmp.filePath).c_str()); if (!stream.is_open() || !stream.good()) { auto errMsg = std::string("Could not read file: ").append(tmp.filePath); std::cerr << errMsg << std::endl; throw std::runtime_error(errMsg); } char s[256]; while (!stream.eof()) { memset(s, 0, sizeof(s)); stream.read(s, 255); tmp.fileData.append(s); } stream.close(); return tmp; }
BOOL WINAPI GaussDIB(LPSTR lpDIBBits, LONG lWidth, LONG lHeight) { // 指向缓存图像的指针 LPSTR lpDst1; LPSTR lpDst2; // 指向缓存DIB图像的指针 LPSTR lpNewDIBBits1; HLOCAL hNewDIBBits1; LPSTR lpNewDIBBits2; HLOCAL hNewDIBBits2; // 模板高度 int iTempH; // 模板宽度 int iTempW; // 模板系数 FLOAT fTempC; // 模板中心元素X坐标 int iTempMX; // 模板中心元素Y坐标 int iTempMY; //模板数组 FLOAT aTemplate[25]; // 暂时分配内存,以保存新图像 hNewDIBBits1 = LocalAlloc(LHND, lWidth * lHeight); if (hNewDIBBits1 == NULL) { // 分配内存失败 return FALSE; } // 锁定内存 lpNewDIBBits1 = (char * )LocalLock(hNewDIBBits1); // 暂时分配内存,以保存新图像 hNewDIBBits2 = LocalAlloc(LHND, lWidth * lHeight); if (hNewDIBBits2 == NULL) { // 分配内存失败 return FALSE; } // 锁定内存 lpNewDIBBits2 = (char * )LocalLock(hNewDIBBits2); // 拷贝源图像到缓存图像中 lpDst1 = (char *)lpNewDIBBits1; memcpy(lpNewDIBBits1, lpDIBBits, lWidth * lHeight); lpDst2 = (char *)lpNewDIBBits2; memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Gauss模板参数 iTempW = 5; iTempH = 5; fTempC = 1.0; iTempMX = 3; iTempMY = 3; aTemplate[0] = -2.0; aTemplate[1] = -4.0; aTemplate[2] = -4.0; aTemplate[3] = -4.0; aTemplate[4] = -2.0; aTemplate[5] = -4.0; aTemplate[6] = 0.0; aTemplate[7] = 8.0; aTemplate[8] = 0.0; aTemplate[9] = -4.0; aTemplate[10] = -4.0; aTemplate[11] = 8.0; aTemplate[12] = 24.0; aTemplate[13] = 8.0; aTemplate[14] = -4.0; aTemplate[15] = -4.0; aTemplate[16] = 0.0; aTemplate[17] = 8.0; aTemplate[18] = 0.0; aTemplate[19] = -4.0; aTemplate[20] = -2.0; aTemplate[21] = -4.0; aTemplate[22] = -4.0; aTemplate[23] = -4.0; aTemplate[24] = -2.0; // 调用Template()函数 if (!Template(lpNewDIBBits1, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } // 复制经过模板运算后的图像到源图像 memcpy(lpDIBBits, lpNewDIBBits1, lWidth * lHeight); // 释放内存 LocalUnlock(hNewDIBBits1); LocalFree(hNewDIBBits1); LocalUnlock(hNewDIBBits2); LocalFree(hNewDIBBits2); // 返回 return TRUE; }
bool TemplateGroup::Refresh() { CString line; CStdioFile file; // Check the date and time stamp. CFileStatus fileStatus; if (!CFile::GetStatus(m_filename, fileStatus)) { return false; } if (m_timeStamp == fileStatus.m_mtime) { // Matches... don't reload. return false; } // Destroy the old stuff. for (size_t i = 0; i < m_templates.GetCount(); i++) delete m_templates[i]; m_templates.RemoveAll(); // Open the file. if (!file.Open(m_filename, CFile::modeRead)) { return false; } // Assign as the new time stamp. m_timeStamp = fileStatus.m_mtime; // Possible states. enum State { FINDTEMPLATE, PARSETEMPLATE, PARSECODE, PARSEMEMO, PARSEDIALOG, PARSEPARAMS, PARSEKEY, }; State state = FINDTEMPLATE; Template* curTemplate = NULL; CString* curDialog = NULL; // Read the template file name. file.ReadString(m_name); int lineNumber = 1; // Go until we're through. while (true) { // Read a line. lineNumber++; if (!file.ReadString(line)) { // End of file. break; } TopState: // Check the state. if (state == FINDTEMPLATE) { // Find the block. if (line.GetLength() >= 1 && line[0] == '[') { if (line[line.GetLength() - 1] == ']') { state = PARSETEMPLATE; curTemplate = WNEW Template(*this); curTemplate->m_lineNumber = lineNumber; m_templates.Add(curTemplate); curTemplate->m_name = line.Mid(1, line.GetLength() - 2); } } } /////////////////////////////////////////////////////////////////////// // Template parsing. /////////////////////////////////////////////////////////////////////// else if (state == PARSETEMPLATE) { ASSERT(curTemplate); // Did we find a new block? if (line.GetLength() >= 1 && line[0] == '[') { curTemplate = NULL; state = FINDTEMPLATE; goto TopState; } // Search for the template sub-type to process. if (line.CompareNoCase("!!code") == 0) { state = PARSECODE; continue; } else if (line.CompareNoCase("!!memo") == 0) { state = PARSEMEMO; continue; } else if (line.CompareNoCase("!!dialog") == 0) { state = PARSEDIALOG; continue; } else if (line.CompareNoCase("!!params") == 0) { state = PARSEPARAMS; continue; } else if (line.CompareNoCase("!!key") == 0) { state = PARSEKEY; continue; } } /////////////////////////////////////////////////////////////////////// // Code parsing /////////////////////////////////////////////////////////////////////// else if (state == PARSECODE) { if (line.CompareNoCase("!!end") == 0) { state = PARSETEMPLATE; continue; } // Add the line to our list. Template::OffsetInfo offsetInfo; offsetInfo.m_offset = curTemplate->m_code.GetLength(); offsetInfo.m_line = lineNumber; curTemplate->m_codeOffsets.Add(offsetInfo); curTemplate->m_code += line; curTemplate->m_code += "\n"; } /////////////////////////////////////////////////////////////////////// // Memo parsing /////////////////////////////////////////////////////////////////////// else if (state == PARSEMEMO) { if (line.CompareNoCase("!!end") == 0) { state = PARSETEMPLATE; continue; } // Add the line to our list. curTemplate->m_memo += line; curTemplate->m_memo += " "; } /////////////////////////////////////////////////////////////////////// // Dialog parsing /////////////////////////////////////////////////////////////////////// else if (state == PARSEDIALOG) { if (line.CompareNoCase("!!end") == 0) { curDialog = NULL; state = PARSETEMPLATE; continue; } if (!curDialog || line.CompareNoCase("!!next") == 0) { int index = curTemplate->m_pages.Add(CString("")); curDialog = &curTemplate->m_pages[index]; if (line.CompareNoCase("!!next") == 0) continue; } if (line.IsEmpty()) { line = "<br>"; } // Add the line to our list. *curDialog += line; *curDialog += " "; } /////////////////////////////////////////////////////////////////////// // Default parameters parsing /////////////////////////////////////////////////////////////////////// else if (state == PARSEPARAMS) { if (line.CompareNoCase("!!end") == 0) { state = PARSETEMPLATE; continue; } // Add the line to our list. LPCTSTR ptr = (LPCTSTR)line; CharArray buffer; CString param = ParseToken(ptr, NULL); while (*ptr != 0 && *ptr == ' ') ptr++; if (*ptr == 0) { // Error!!! } Template::DefaultInfo info; info.m_entry = param; info.m_value = ptr; curTemplate->m_defaults.AddTail(info); } /////////////////////////////////////////////////////////////////////// // Default parameters parsing /////////////////////////////////////////////////////////////////////// else if (state == PARSEKEY) { state = PARSETEMPLATE; // Get the keys. LPCTSTR ptr = (LPCTSTR)line; CharArray buffer; CString param = ParseToken(ptr, NULL); curTemplate->m_key = param; } } // Close the template file. file.Close(); return true; }
HBITMAP CDlgTemplate::PicTemplate() { return Template(m_dib.pcol,m_dib.bm,m_dib.RGB32BITSBITMAPINFO); }
CValue CValueText::Method(int iName,CValue **p) { CValue Ret; switch(iName) { case enLinesCnt: Ret=aText.GetSize(); break; case enClear: aText.RemoveAll(); break; case enGetLine: { DEF_N_LINE() Ret=String(aText[n]); break; } case enAddLine: if (nTemplate) aText.Add(Template(p[0]->GetString())); else aText.Add(p[0]->GetString()); break; case enReplaceLine: { DEF_N_LINE() if (nTemplate) aText[n]=Template(p[1]->GetString()); else aText[n]=p[1]->GetString(); break; } case enDeleteLine: { DEF_N_LINE() aText.RemoveAt(n); break; } case enInsertLine: { DEF_N_LINE() if (nTemplate) aText.InsertAt(n,Template(p[1]->GetString())); else aText.InsertAt(n,p[1]->GetString()); break; } case enOpen: { CString csName=p[0]->GetString(); if(!FileExist(csName)) Error(CString("Файл ")+csName+" не найден"); aText.RemoveAll(); csTitle=csName; int nSize=0; char *buf=LoadFromFileBin(csName,nSize); if (!nSize) break; if(buf) { CString Str; Str.GetBuffer(10000); for(int i=0;i<nSize;i++) { if(buf[i]==0x0D&&buf[i+1]==0x0A) { if (nTemplate) aText.Add(Template(Str)); else aText.Add(Str); Str=""; i++; //i++; } else { Str+=buf[i]; } } if (nTemplate) aText.Add(Template(Str)); else aText.Add(Str); Str.ReleaseBuffer(); delete []buf; } break; } case enShow: { if(!pDoc) pDoc=(CModuleDoc*)OpenFormMDI("Модуль",1); pDoc->SetPathName(csTitle,0); pDoc->SetTitle(csTitle); pDoc->SetText(GetStr()); pDoc->m_xTextBuffer.SetReadOnly(bReadOnly); break; } case enWrite: { CString csName=p[0]->GetString(); csTitle=csName; extern void WritoToFileText(CString csCFile,CString Str); WritoToFileText(csName,GetStr()); break; } case enReadOnly: { Ret=bReadOnly; bReadOnly=p[0]->GetNumber(); if(pDoc) pDoc->m_xTextBuffer.SetReadOnly(bReadOnly); break; } case enCodePage: { Ret=nCodePage; if (p[0]->nType) nCodePage=p[0]->GetNumber(); break; } case enTemplate: { Ret=nTemplate; if (p[0]->nType) nTemplate=p[0]->GetNumber(); break; } case enFixTemplate: { Ret=nFixTemplate; if (p[0]->nType) nFixTemplate=p[0]->GetNumber(); break; } case enGetText: Ret=String(GetStr()); break; } return Ret; }
BOOL WINAPI KirschDIB(LPSTR lpDIBBits, LONG lWidth, LONG lHeight) { // 指向缓存图像的指针 LPSTR lpDst1; LPSTR lpDst2; // 指向缓存DIB图像的指针 LPSTR lpNewDIBBits1; HLOCAL hNewDIBBits1; LPSTR lpNewDIBBits2; HLOCAL hNewDIBBits2; //循环变量 long i; long j; // 模板高度 int iTempH; // 模板宽度 int iTempW; // 模板系数 FLOAT fTempC; // 模板中心元素X坐标 int iTempMX; // 模板中心元素Y坐标 int iTempMY; //模板数组 FLOAT aTemplate[9]; // 暂时分配内存,以保存新图像 hNewDIBBits1 = LocalAlloc(LHND, lWidth * lHeight); if (hNewDIBBits1 == NULL) { // 分配内存失败 return FALSE; } // 锁定内存 lpNewDIBBits1 = (char * )LocalLock(hNewDIBBits1); // 暂时分配内存,以保存新图像 hNewDIBBits2 = LocalAlloc(LHND, lWidth * lHeight); if (hNewDIBBits2 == NULL) { // 分配内存失败 return FALSE; } // 锁定内存 lpNewDIBBits2 = (char * )LocalLock(hNewDIBBits2); // 拷贝源图像到缓存图像中 lpDst1 = (char *)lpNewDIBBits1; memcpy(lpNewDIBBits1, lpDIBBits, lWidth * lHeight); lpDst2 = (char *)lpNewDIBBits2; memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板1参数 iTempW = 3; iTempH = 3; fTempC = 1.0; iTempMX = 1; iTempMY = 1; aTemplate[0] = 5.0; aTemplate[1] = 5.0; aTemplate[2] = 5.0; aTemplate[3] = -3.0; aTemplate[4] = 0.0; aTemplate[5] = -3.0; aTemplate[6] = -3.0; aTemplate[7] = -3.0; aTemplate[8] = -3.0; // 调用Template()函数 if (!Template(lpNewDIBBits1, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } // 设置Kirsch模板2参数 aTemplate[0] = -3.0; aTemplate[1] = 5.0; aTemplate[2] = 5.0; aTemplate[3] = -3.0; aTemplate[4] = 0.0; aTemplate[5] = 5.0; aTemplate[6] = -3.0; aTemplate[7] = -3.0; aTemplate[8] = -3.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板3参数 aTemplate[0] = -3.0; aTemplate[1] = -3.0; aTemplate[2] = 5.0; aTemplate[3] = -3.0; aTemplate[4] = 0.0; aTemplate[5] = 5.0; aTemplate[6] = -3.0; aTemplate[7] = -3.0; aTemplate[8] = 5.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板4参数 aTemplate[0] = -3.0; aTemplate[1] = -3.0; aTemplate[2] = -3.0; aTemplate[3] = -3.0; aTemplate[4] = 0.0; aTemplate[5] = 5.0; aTemplate[6] = -3.0; aTemplate[7] = 5.0; aTemplate[8] = 5.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板5参数 aTemplate[0] = -3.0; aTemplate[1] = -3.0; aTemplate[2] = -3.0; aTemplate[3] = -3.0; aTemplate[4] = 0.0; aTemplate[5] = -3.0; aTemplate[6] = 5.0; aTemplate[7] = 5.0; aTemplate[8] = 5.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板6参数 aTemplate[0] = -3.0; aTemplate[1] = -3.0; aTemplate[2] = -3.0; aTemplate[3] = 5.0; aTemplate[4] = 0.0; aTemplate[5] = -3.0; aTemplate[6] = 5.0; aTemplate[7] = 5.0; aTemplate[8] = -3.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板7参数 aTemplate[0] = 5.0; aTemplate[1] = -3.0; aTemplate[2] = -3.0; aTemplate[3] = 5.0; aTemplate[4] = 0.0; aTemplate[5] = -3.0; aTemplate[6] = 5.0; aTemplate[7] = -3.0; aTemplate[8] = -3.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 拷贝源图像到缓存图像中 memcpy(lpNewDIBBits2, lpDIBBits, lWidth * lHeight); // 设置Kirsch模板8参数 aTemplate[0] = 5.0; aTemplate[1] = 5.0; aTemplate[2] = -3.0; aTemplate[3] = 5.0; aTemplate[4] = 0.0; aTemplate[5] = -3.0; aTemplate[6] = -3.0; aTemplate[7] = -3.0; aTemplate[8] = -3.0; // 调用Template()函数 if (!Template(lpNewDIBBits2, lWidth, lHeight, iTempH, iTempW, iTempMX, iTempMY, aTemplate, fTempC)) { return FALSE; } //求两幅缓存图像的最大值 for(j = 0; j <lHeight; j++) { for(i = 0;i <lWidth-1; i++) { // 指向缓存图像1倒数第j行,第i个象素的指针 lpDst1 = (char *)lpNewDIBBits1 + lWidth * j + i; // 指向缓存图像2倒数第j行,第i个象素的指针 lpDst2 = (char *)lpNewDIBBits2 + lWidth * j + i; if(*lpDst2 > *lpDst1) *lpDst1 = *lpDst2; } } // 复制经过模板运算后的图像到源图像 memcpy(lpDIBBits, lpNewDIBBits1, lWidth * lHeight); // 释放内存 LocalUnlock(hNewDIBBits1); LocalFree(hNewDIBBits1); LocalUnlock(hNewDIBBits2); LocalFree(hNewDIBBits2); // 返回 return TRUE; }