CvxText.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. #include "pch.h"
  2. #include "CvxText.h"
  3. #include <json/json.h>
  4. #include "BaseUtility.h"
  5. #include <iostream>
  6. #include <fstream>
  7. using namespace std;
  8. using namespace cv;
  9. #if defined(GNUC)
  10. #pragma GCC diagnostic push
  11. #pragma GCC diagnostic ignored “-Wdeprecated-declarations”
  12. #elif defined(_MSC_VER)
  13. #pragma warning(disable : 4996)
  14. #endif
  15. void GetStringSize(HDC hDC, const char* str, int* w, int* h)
  16. {
  17. SIZE size;
  18. GetTextExtentPoint32A(hDC, str, strlen(str), &size);
  19. if (w != 0) *w = size.cx;
  20. if (h != 0) *h = size.cy;
  21. }
  22. cv::Size GetTextSize(const char* str, int fontSize, const char* fn, bool italic, bool underline)
  23. {
  24. HDC hDC = CreateCompatibleDC(0);
  25. LOGFONTA lf;
  26. lf.lfHeight = -fontSize;
  27. lf.lfWidth = 0;
  28. lf.lfEscapement = 0;
  29. lf.lfOrientation = 0;
  30. lf.lfWeight = 5;
  31. lf.lfItalic = italic; //斜体
  32. lf.lfUnderline = underline; //下划线
  33. lf.lfStrikeOut = 0;
  34. lf.lfCharSet = DEFAULT_CHARSET;
  35. lf.lfOutPrecision = 0;
  36. lf.lfClipPrecision = 0;
  37. lf.lfQuality = PROOF_QUALITY;
  38. lf.lfPitchAndFamily = 0;
  39. strcpy_s(lf.lfFaceName, fn);
  40. HFONT hf = CreateFontIndirectA(&lf);
  41. HFONT hOldFont = (HFONT)SelectObject(hDC, hf);
  42. int strBaseW = 0, strBaseH = 0;
  43. int singleRow = 0;
  44. char buf[1 << 12];
  45. strcpy_s(buf, str);
  46. char *bufT[1 << 12]; // 这个用于分隔字符串后剩余的字符,可能会超出。
  47. //处理多行
  48. {
  49. int nnh = 0;
  50. int cw, ch;
  51. const char* ln = strtok_s(buf, "\n", bufT);
  52. while (ln != 0)
  53. {
  54. GetStringSize(hDC, ln, &cw, &ch);
  55. strBaseW = max(strBaseW, cw);
  56. strBaseH = max(strBaseH, ch);
  57. ln = strtok_s(0, "\n", bufT);
  58. nnh++;
  59. }
  60. singleRow = strBaseH;
  61. strBaseH *= nnh;
  62. }
  63. SelectObject(hDC, hOldFont);
  64. DeleteObject(hf);
  65. DeleteDC(hDC);
  66. cv::Size size;
  67. size.width = strBaseW;
  68. size.height = strBaseH;
  69. return size;
  70. }
  71. void putTextZH(cv::Mat &dst, cv::Size & rSize, const char* str, Point org, Scalar color, int fontSize, const char* fn, bool italic, bool underline)
  72. {
  73. CV_Assert(dst.data != 0 && (dst.channels() == 1 || dst.channels() == 3));
  74. int x, y, r, b;
  75. if (org.x > dst.cols || org.y > dst.rows) return;
  76. x = org.x < 0 ? -org.x : 0;
  77. y = org.y < 0 ? -org.y : 0;
  78. LOGFONTA lf;
  79. lf.lfHeight = -fontSize;
  80. lf.lfWidth = 0;
  81. lf.lfEscapement = 0;
  82. lf.lfOrientation = 0;
  83. lf.lfWeight = 5;
  84. lf.lfItalic = italic; //斜体
  85. lf.lfUnderline = underline; //下划线
  86. lf.lfStrikeOut = 0;
  87. lf.lfCharSet = DEFAULT_CHARSET;
  88. lf.lfOutPrecision = 0;
  89. lf.lfClipPrecision = 0;
  90. lf.lfQuality = PROOF_QUALITY;
  91. lf.lfPitchAndFamily = 0;
  92. strcpy_s(lf.lfFaceName, fn);
  93. HFONT hf = CreateFontIndirectA(&lf);
  94. HDC hDC = CreateCompatibleDC(0);
  95. HFONT hOldFont = (HFONT)SelectObject(hDC, hf);
  96. int strBaseW = 0, strBaseH = 0;
  97. int singleRow = 0;
  98. char buf[1 << 12];
  99. strcpy_s(buf, str);
  100. char *bufT[1 << 12]; // 这个用于分隔字符串后剩余的字符,可能会超出。
  101. //处理多行
  102. {
  103. int nnh = 0;
  104. int cw, ch;
  105. const char* ln = strtok_s(buf, "\n", bufT);
  106. while (ln != 0)
  107. {
  108. GetStringSize(hDC, ln, &cw, &ch);
  109. strBaseW = max(strBaseW, cw);
  110. strBaseH = max(strBaseH, ch);
  111. ln = strtok_s(0, "\n", bufT);
  112. nnh++;
  113. }
  114. singleRow = strBaseH;
  115. strBaseH *= nnh;
  116. }
  117. rSize.width = strBaseW;
  118. rSize.height = strBaseH;
  119. if (org.x + strBaseW < 0 || org.y + strBaseH < 0)
  120. {
  121. SelectObject(hDC, hOldFont);
  122. DeleteObject(hf);
  123. DeleteObject(hDC);
  124. return;
  125. }
  126. r = org.x + strBaseW > dst.cols ? dst.cols - org.x - 1 : strBaseW - 1;
  127. b = org.y + strBaseH > dst.rows ? dst.rows - org.y - 1 : strBaseH - 1;
  128. org.x = org.x < 0 ? 0 : org.x;
  129. org.y = org.y < 0 ? 0 : org.y;
  130. BITMAPINFO bmp = { 0 };
  131. BITMAPINFOHEADER& bih = bmp.bmiHeader;
  132. int strDrawLineStep = strBaseW * 3 % 4 == 0 ? strBaseW * 3 : (strBaseW * 3 + 4 - ((strBaseW * 3) % 4));
  133. bih.biSize = sizeof(BITMAPINFOHEADER);
  134. bih.biWidth = strBaseW;
  135. bih.biHeight = strBaseH;
  136. bih.biPlanes = 1;
  137. bih.biBitCount = 24;
  138. bih.biCompression = BI_RGB;
  139. bih.biSizeImage = strBaseH * strDrawLineStep;
  140. bih.biClrUsed = 0;
  141. bih.biClrImportant = 0;
  142. void* pDibData = 0;
  143. HBITMAP hBmp = CreateDIBSection(hDC, &bmp, DIB_RGB_COLORS, &pDibData, 0, 0);
  144. CV_Assert(pDibData != 0);
  145. HBITMAP hOldBmp = (HBITMAP)SelectObject(hDC, hBmp);
  146. //color.val[2], color.val[1], color.val[0]
  147. SetTextColor(hDC, RGB(255, 255, 255));
  148. SetBkColor(hDC, 0);
  149. //SetStretchBltMode(hDC, COLORONCOLOR);
  150. strcpy_s(buf, str);
  151. const char* ln = strtok_s(buf, "\n", bufT);
  152. int outTextY = 0;
  153. while (ln != 0)
  154. {
  155. TextOutA(hDC, 0, outTextY, ln, strlen(ln));
  156. outTextY += singleRow;
  157. ln = strtok_s(0, "\n", bufT);
  158. }
  159. uchar* dstData = (uchar*)dst.data;
  160. int dstStep = dst.step / sizeof(dstData[0]);
  161. unsigned char* pImg = (unsigned char*)dst.data + org.x * dst.channels() + org.y * dstStep;
  162. unsigned char* pStr = (unsigned char*)pDibData + x * 3;
  163. for (int tty = y; tty <= b; ++tty)
  164. {
  165. unsigned char* subImg = pImg + (tty - y) * dstStep;
  166. unsigned char* subStr = pStr + (strBaseH - tty - 1) * strDrawLineStep;
  167. for (int ttx = x; ttx <= r; ++ttx)
  168. {
  169. for (int n = 0; n < dst.channels(); ++n) {
  170. double vtxt = subStr[n] / 255.0;
  171. int cvv = vtxt * color.val[n] + (1 - vtxt) * subImg[n];
  172. subImg[n] = cvv > 255 ? 255 : (cvv < 0 ? 0 : cvv);
  173. }
  174. subStr += 3;
  175. subImg += dst.channels();
  176. }
  177. }
  178. SelectObject(hDC, hOldBmp);
  179. SelectObject(hDC, hOldFont);
  180. DeleteObject(hf);
  181. DeleteObject(hBmp);
  182. DeleteDC(hDC);
  183. }
  184. ///////////////////////////// 数据收集卡 ///////////////////////////////////////
  185. // 获取字符串的画布上的宽度
  186. int getLineStrWidth(string str, int fontSize, int ttBoxW, int tiSl, int backPix) {
  187. int iw = str.length()*fontSize*0.5;
  188. iw += ttBoxW;
  189. iw += tiSl;
  190. iw += backPix;
  191. iw += fontSize * 1.5; // 题号的宽度 最多不超过1.5个字体宽度 56.
  192. return iw;
  193. }
  194. // 转码 utf-8 2 ansi
  195. static void UTF82ANSI(LPCSTR lpBuff, int nLen, char* pData, int iMaxLen)
  196. {
  197. ZeroMemory(pData, sizeof(char)*iMaxLen);
  198. int nCont = MultiByteToWideChar(CP_UTF8, 0, lpBuff, nLen, NULL, 0);
  199. WCHAR* szTemp = new WCHAR[nCont + 1];
  200. ZeroMemory(szTemp, sizeof(WCHAR)*(nCont + 1));
  201. MultiByteToWideChar(CP_UTF8, 0, lpBuff, nLen, szTemp, nCont);
  202. //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的
  203. int len = WideCharToMultiByte(CP_ACP, 0, szTemp, nCont, NULL, 0, NULL, NULL);
  204. if (len < iMaxLen) {
  205. WideCharToMultiByte(CP_ACP, 0, szTemp, nCont, pData, len, NULL, NULL);
  206. }
  207. else {
  208. char* buffer = new char[len + 1];
  209. //宽字节编码转换成多字节编码
  210. WideCharToMultiByte(CP_ACP, 0, szTemp, nCont, buffer, len, NULL, NULL);
  211. buffer[len] = '\0';
  212. //删除缓冲区并返回值
  213. strncpy(pData, buffer, iMaxLen - 1);
  214. delete[] buffer;
  215. buffer = NULL;
  216. }
  217. delete[]szTemp;
  218. szTemp = NULL;
  219. }
  220. // 二进制码生成获取
  221. void createBinString(Mat & img, int pageNum, int ptw, int pth, cv::Point ptStart, vector<cv::Rect>& vecBoxPages) {
  222. vector<int> vecBinStr; vecBinStr.resize(12);
  223. for (size_t i = 11; i > 0; i--) {
  224. int ys = pageNum % 2;
  225. vecBinStr[i] = ys;
  226. pageNum = pageNum / 2;
  227. }
  228. vecBoxPages.clear();
  229. int ptPgW = ptw / 2; int ptPgH = pth / 2;
  230. for (int j = 0; j < 3; j++) {
  231. int _startY = ptStart.y + 15 + 50 * j;
  232. for (int i = 0; i < 4; i++) {
  233. int _startX = ptStart.x + 18 + i * 72;
  234. vecBoxPages.push_back(cv::Rect(_startX, _startY, ptPgW, ptPgH));
  235. if (vecBinStr[j * 4 + i])
  236. rectangle(img, vecBoxPages[vecBoxPages.size() - 1], cv::Scalar(0), -1);
  237. else
  238. rectangle(img, vecBoxPages[vecBoxPages.size() - 1], cv::Scalar(200, 200, 200), 2, 8, 0);
  239. }
  240. }
  241. return;
  242. }
  243. void generatePageJson(vector<cv::Rect>& vecPts, vector<cv::Rect>& vecBoxPages)
  244. {
  245. Json::Value imageSize;
  246. imageSize["width"] = 1654;
  247. imageSize["height"] = 2344;
  248. Json::Value location(Json::arrayValue);
  249. for (auto& iter : vecPts)
  250. {
  251. Json::Value item;
  252. item["x"] = iter.x;
  253. item["y"] = iter.y;
  254. item["width"] = iter.width;
  255. item["height"] = iter.height;
  256. location.append(item);
  257. }
  258. Json::Value pagenumber(Json::arrayValue);
  259. int nSubVecSize = 4;// 每个小vector的容量
  260. for (size_t i = 0, j = 1; i < vecBoxPages.size(); i += nSubVecSize)
  261. {
  262. vector<cv::Rect> vecSmall;
  263. auto last = std::min(vecBoxPages.size(), i + nSubVecSize);
  264. vecSmall.insert(vecSmall.begin(), vecBoxPages.begin() + i, vecBoxPages.begin() + last);
  265. Json::Value opt(Json::arrayValue);
  266. std::string choice[] = { "A", "B", "C", "D" };
  267. for (int h = 0; h < vecSmall.size(); h++)
  268. {
  269. Json::Value bin;
  270. bin["x"] = vecSmall[h].x;
  271. bin["y"] = vecSmall[h].y;
  272. bin["width"] = vecSmall[h].width;
  273. bin["height"] = vecSmall[h].height;
  274. bin["optName"] = choice[h];
  275. opt.append(bin);
  276. }
  277. Json::Value item;
  278. item["id"] = j;
  279. item["opt"] = opt;
  280. pagenumber.append(item);
  281. j++;
  282. }
  283. Json::Value itemRoot;
  284. itemRoot["imageSize"] = imageSize;
  285. itemRoot["location"] = location;
  286. itemRoot["pagenumber"] = pagenumber;
  287. Json::FastWriter writer;
  288. std::string strJson = writer.write(itemRoot);
  289. CFile zip;
  290. zip.Open(_T("D:\\page.json"), CFile::modeCreate | CFile::modeWrite);
  291. DWORD wide_string_len = MultiByteToWideChar(CP_ACP, 0, strJson.c_str(), -1, NULL, 0);
  292. WCHAR* wide_string = new WCHAR[wide_string_len];
  293. wide_string_len = MultiByteToWideChar(CP_ACP, 0, strJson.c_str(), -1, wide_string, wide_string_len);
  294. DWORD utf8_string_len = WideCharToMultiByte(CP_UTF8, 0, wide_string, -1, NULL, 0, NULL, NULL);
  295. CHAR* utf8_string = new CHAR[utf8_string_len];
  296. utf8_string_len = WideCharToMultiByte(CP_UTF8, 0, wide_string, -1, utf8_string, utf8_string_len, NULL, NULL);
  297. zip.Write((void*)utf8_string, utf8_string_len - 1);
  298. // LOG4CPLUS_INFO_FMT(pTestLogger, LOG4CPLUS_TEXT("%s"), CString(json_str.c_str()));
  299. delete wide_string;
  300. delete utf8_string;
  301. zip.Close();
  302. }
  303. std::string JsonToString(const Json::Value & root)
  304. {
  305. static Json::Value def = []{
  306. Json::Value def;
  307. Json::StreamWriterBuilder::setDefaults(&def);
  308. def["emitUTF8"] = true;
  309. return def;
  310. }();
  311. std::ostringstream stream;
  312. Json::StreamWriterBuilder stream_builder;
  313. stream_builder.settings_ = def;//Config emitUTF8
  314. std::unique_ptr<Json::StreamWriter> writer(stream_builder.newStreamWriter());
  315. writer->write(root, &stream);
  316. return stream.str();
  317. }
  318. int dataCollectionPaper(int cols, int index, int fontSize, int lineGrayPix, bool engShow, std::vector<string>& vecLines, CString dir, std::string& strPngPath) {
  319. /* 这里要做一些栏数 和 vecLines的对应值确认 */
  320. if (2 == cols && 14 * 2 == vecLines.size())
  321. ; // ok
  322. if (3 == cols && 14 * 3 == vecLines.size())
  323. ; // ok
  324. if (4 == cols && 14 * 4 == vecLines.size())
  325. ; // ok
  326. // 生成画布图像
  327. cv::Mat img(cv::Size(1654, 2344), CV_8UC3, cv::Scalar(255, 255, 255));
  328. int ptw = 80; int pth = 40;
  329. cv::Size fSize(0, 0);
  330. int leftPos = 100, rightPos = 1450;
  331. int topPos = 90;
  332. int fontW = rightPos - leftPos + ptw;
  333. vector<cv::Rect> vecPts = {
  334. cv::Rect(100,90,ptw,pth),
  335. cv::Rect(580,90,ptw,pth),
  336. cv::Rect(1450,90,ptw,pth),
  337. cv::Rect(100,2176,ptw,pth),
  338. cv::Rect(1450,2176,ptw,pth),
  339. };
  340. // 画定位点
  341. for (size_t i = 0; i < vecPts.size(); i++)
  342. {
  343. rectangle(img, vecPts[i], cv::Scalar(0, 0, 0), -1);
  344. }
  345. // 画示例框
  346. topPos += pth; topPos += 30;
  347. rectangle(img, cv::Rect(leftPos, topPos, fontW, 200), cv::Scalar(0, 0, 0), 2, 8, 0);
  348. // 画页码框
  349. cv::Rect boxPageNumber(leftPos + fontW - 300, topPos, 300, 200);
  350. rectangle(img, boxPageNumber, cv::Scalar(0, 0, 0), 2, 8, 0);
  351. // 生成二进制码流
  352. /* 二进制码流的坐标在下面函数里面实现,需要用书写获取 */
  353. vector<cv::Rect> vecBoxPages;
  354. createBinString(img, index, ptw, pth, cv::Point(boxPageNumber.x, boxPageNumber.y), vecBoxPages);
  355. string strPageNumInfo = "关联ID: " + to_string(index);
  356. putTextZH(img, fSize, strPageNumInfo.c_str(), cv::Point(boxPageNumber.x + 100, boxPageNumber.y + 50 * 2 + 20 + 15 + 15 + 15), Scalar(0), 20, "宋体");
  357. // 生成page.json
  358. //generatePageJson(vecPts, vecBoxPages);
  359. // 画警示信息
  360. string strMesInfo = "1、请在每题下方的横线上书写本题的内容!\
  361. \n\n2、题号不需要书写,标点符号需要原样书写。☆\
  362. \n\n3、如果本题书写有误,进行了涂抹修改等操作,请将题号前矩形框用任意笔进行填涂!☆☆\n";
  363. putTextZH(img, fSize, strMesInfo.c_str(), cv::Point(leftPos + 20, topPos + 20), Scalar(0), 25, "宋体");
  364. int lineTop1 = topPos + 20 + fSize.height + 20;
  365. cv::line(img, cv::Point(leftPos, lineTop1), cv::Point(rightPos + ptw - 300, topPos + 20 + fSize.height + 20), Scalar(0), 2, 8, 0);
  366. // 正确示例
  367. string strEgInfo = "正\n确\n示\n例";
  368. putTextZH(img, fSize, strEgInfo.c_str(), cv::Point(leftPos + 20, topPos + 20 + fSize.height + 20 + 3), Scalar(0), 20, "宋体");
  369. cv::line(img, cv::Point(leftPos + 20 + fSize.width + 10, lineTop1), cv::Point(leftPos + 20 + fSize.width + 10, topPos + 200), Scalar(0, 0, 0), 2, 8, 0);
  370. // 贴图区域
  371. /* 暂不实现 */
  372. topPos += 200;
  373. // 文字区域
  374. static int maxLineNum = 14; // 最大行数14
  375. static int ttBoxWidth = 30; // 填涂框的边长
  376. static int tiSl = 10; // 题号和题干间的距离
  377. static int lineDis = 20; // 两行之间的距离
  378. int colWidth = fontW / cols; // 单栏的宽度
  379. fSize.width = 0; fSize.height = 0;
  380. Json::Value root(Json::arrayValue);
  381. for (int col = 0; col < cols; col++)
  382. { // 逐栏画题
  383. int colTopPos = topPos;
  384. int colLeftPos = leftPos + col * colWidth;
  385. for (size_t i = 0; i < maxLineNum; i++)
  386. {
  387. size_t vecIndex = i + col * maxLineNum;
  388. if (vecIndex >= vecLines.size())
  389. {
  390. break;
  391. }
  392. colTopPos += lineDis;
  393. int lineLen = ttBoxWidth + tiSl;
  394. // 画填涂框 30*30 大小
  395. cv::Rect rcbox(colLeftPos, colTopPos, ttBoxWidth, ttBoxWidth);
  396. rectangle(img, rcbox, cv::Scalar(0), 1, 8, 0);
  397. int iQNum = i + 1 + col * maxLineNum;
  398. string strStinfo = to_string(iQNum); strStinfo += ".";
  399. cv::Point ptNum(colLeftPos + ttBoxWidth + tiSl, colTopPos);
  400. putTextZH(img, fSize, strStinfo.c_str(), ptNum, Scalar(0, 0, 0), fontSize, "宋体"); // 跟填涂框保持10px距离
  401. lineLen += fSize.width;
  402. cv::Rect rcNum(ptNum.x, ptNum.y, fSize.width, fSize.height);
  403. strStinfo.clear();
  404. string strTgInfo = vecLines[vecIndex];
  405. if (!engShow)
  406. ; /* 移除词性 */
  407. //char szTemp[2048];
  408. //memset(szTemp, 0, sizeof(char)*(2048));
  409. //UTF82ANSI(strTgInfo.c_str(), strTgInfo.length(), szTemp, 2048);
  410. //strTgInfo = szTemp;
  411. cv::Point ptQues(colLeftPos + ttBoxWidth + tiSl + fSize.width, colTopPos);
  412. putTextZH(img, fSize, strTgInfo.c_str(), ptQues, Scalar(0, 0, 0), fontSize, "宋体"); // 跟填涂框保持10px距离
  413. lineLen += fSize.width;
  414. cv::Rect rcQues(ptQues.x, ptQues.y, fSize.width, fSize.height);
  415. cv::Rect rcAns(colLeftPos + 30, colTopPos + fSize.height, colWidth - ttBoxWidth, 1);
  416. colTopPos = colTopPos + fSize.height * 3.5; //两行之间两倍的距离用于书写
  417. line(img, cv::Point(colLeftPos + 30, colTopPos), cv::Point(colLeftPos + colWidth - 1, colTopPos), Scalar(lineGrayPix, lineGrayPix, lineGrayPix), 1, 8, 0);
  418. rcAns.height = colTopPos - rcAns.y + lineDis;
  419. //生成识别信息
  420. Json::Value ttbox;
  421. ttbox["x"] = rcbox.x;
  422. ttbox["y"] = rcbox.y;
  423. ttbox["width"] = rcbox.width;
  424. ttbox["height"] = rcbox.height;
  425. Json::Value queNum;
  426. queNum["x"] = rcNum.x;
  427. queNum["y"] = rcNum.y;
  428. queNum["width"] = rcNum.width;
  429. queNum["height"] = rcNum.height;
  430. Json::Value queInfo;
  431. queInfo["x"] = rcQues.x;
  432. queInfo["y"] = rcQues.y;
  433. queInfo["width"] = rcQues.width;
  434. queInfo["height"] = rcQues.height;
  435. queInfo["info"] = strTgInfo.c_str();
  436. Json::Value ansInfo;
  437. ansInfo["x"] = rcAns.x;
  438. ansInfo["y"] = rcAns.y;
  439. ansInfo["width"] = rcAns.width;
  440. ansInfo["height"] = rcAns.height;
  441. Json::Value item;
  442. item["id"] = iQNum;
  443. item["ttbox"] = ttbox;
  444. item["queNum"] = queNum;
  445. item["queInfo"] = queInfo;
  446. item["ansInfo"] = ansInfo;
  447. root.append(item);
  448. // test
  449. /*rectangle(img, rcbox, cv::Scalar(0, 0, 200), 1, 8, 0);
  450. rectangle(img, rcNum, cv::Scalar(0, 200, 0), 1, 8, 0);
  451. rectangle(img, rcQues, cv::Scalar(100, 0, 0), 1, 8, 0);
  452. rectangle(img, rcAns, cv::Scalar(200, 0, 0), 1, 8, 0);*/
  453. }
  454. }
  455. std::string strJson = JsonToString(root);
  456. CString strTemplatePath;
  457. strTemplatePath.Format(L"%s/json/%d.json", dir, index);
  458. CFile zip;
  459. zip.Open(strTemplatePath, CFile::modeCreate | CFile::modeWrite);
  460. zip.Write((void*)strJson.c_str(), strJson.length());
  461. zip.Close();
  462. wchar_t tempPath[MAX_PATH];
  463. DWORD dwSize = MAX_PATH;
  464. GetTempPath(dwSize, tempPath);//获取临时文件夹路径
  465. static int tmp_index = 1;
  466. wchar_t szPath[MAX_PATH];
  467. _stprintf(szPath, L"%stmp_%d.png", tempPath, tmp_index);
  468. tmp_index++;
  469. if (tmp_index > 10)
  470. {
  471. tmp_index = 1;
  472. }
  473. strPngPath = TstringToGB2312(szPath);
  474. cv::imwrite(strPngPath, img);
  475. /*cv::namedWindow("fuck", 1);
  476. cv::imshow("fuck", img);
  477. cv::waitKey(0);*/
  478. return 0;
  479. }
  480. int get_gray_num(cv::Mat & img, cv::Rect & box, int &meanGray, int threshold) {
  481. uchar * ptr;
  482. int count = 0;
  483. long long totalGrayNum = 0;
  484. for (int h = box.y; h < box.y + box.height; h++) {
  485. ptr = img.ptr<uchar>(h);
  486. for (int w = box.x; w < box.x + box.width; w++) {
  487. int pix = static_cast<int>(ptr[w]);
  488. totalGrayNum += pix;
  489. if (pix < threshold)
  490. count++;
  491. }
  492. }
  493. meanGray = totalGrayNum / box.area();
  494. return count;
  495. }
  496. int get_around_box_gray(cv::Mat & img, cv::Rect & box) {
  497. int left = (box.x - box.width / 2) > 0 ? (box.x - box.width / 2) : 0;
  498. int top = (box.y - box.height / 2) > 0 ? (box.y - box.height / 2) : 0;
  499. int right = (box.x + box.width * 3 / 2) < (img.cols - 1) ? (box.x + box.width * 3 / 2) : (img.cols - 1);
  500. int bottom = (box.y + box.height * 3 / 2) < (img.rows - 1) ? (box.y + box.height * 3 / 2) : (img.rows - 1);
  501. uchar * ptr;
  502. std::int64_t total = 0;
  503. int number = 0;
  504. for (int h = top; h < bottom; h++) {
  505. ptr = img.ptr<uchar>(h);
  506. for (int w = left; w < right; w++) {
  507. if (w > box.x && w<(box.x + box.width) && h>box.y&&h < (box.y + box.height))
  508. continue;
  509. total += static_cast<std::int64_t>(ptr[w]);
  510. number++;
  511. }
  512. }
  513. return static_cast<int>(total / number);
  514. }
  515. #define USE_THRESHOLD_VAL 200
  516. bool analysis_ttbox_mark(cv::Mat & imgSrc, cv::Rect & rc) {
  517. int thre = min(200, max(get_around_box_gray(imgSrc, rc), 160));
  518. int gray = get_gray_num(imgSrc, rc, thre, USE_THRESHOLD_VAL);
  519. double ds = gray * 1.0 / rc.area()*1.0;
  520. if (ds > 0.50)
  521. return true;
  522. return false;
  523. }
  524. int cutPaper(int pageNum, std::string strJsonPath, std::string strPaperPath, std::string strSavePath)
  525. {
  526. ifstream in(strJsonPath, ios::binary);
  527. if (!in.is_open())
  528. {
  529. return 1;
  530. }
  531. Json::Features features;
  532. Json::Reader reader(features);
  533. Json::Value root;
  534. if (!reader.parse(in, root))
  535. {
  536. return 1;
  537. }
  538. if (!root.isArray())
  539. {
  540. return 1;
  541. }
  542. cv::Mat src = cv::imread(strPaperPath);
  543. if (src.empty())
  544. {
  545. return 1;
  546. }
  547. auto pfGetPos = [](const Json::Value & value, cv::Rect& rc) {
  548. int x = 0, y = 0, w = 0, h = 0;
  549. if (value.isMember("x"))
  550. {
  551. x = value["x"].asInt();
  552. }
  553. if (value.isMember("y"))
  554. {
  555. y = value["y"].asInt();
  556. }
  557. if (value.isMember("width"))
  558. {
  559. w = value["width"].asInt();
  560. }
  561. if (value.isMember("height"))
  562. {
  563. h = value["height"].asInt();
  564. }
  565. rc = cv::Rect(x, y, w, h);
  566. };
  567. for (int i = 0; i < root.size(); i++)
  568. {
  569. Json::Value row = root[i];
  570. std::string id = row["id"].asString();
  571. std::string info = row["queInfo"]["info"].asString();
  572. Json::Value ttbox = row["ttbox"];
  573. Json::Value ansInfo = row["ansInfo"];
  574. cv::Rect rc_ttbox;
  575. cv::Rect rc_ansInfo;
  576. pfGetPos(ttbox, rc_ttbox);
  577. pfGetPos(ansInfo, rc_ansInfo);
  578. // 选择框灰度判断
  579. bool ret = analysis_ttbox_mark(src, rc_ttbox);
  580. char szTxtPath[MAX_PATH] = { 0 };
  581. char szJpgPath[MAX_PATH] = { 0 };
  582. DWORD dwCount = GetTickCount();
  583. sprintf(szTxtPath, "%s\\%s\\%d_%s_%ld.txt", strSavePath.c_str(), ret ? "abnormal" : "normal", pageNum, id.c_str(), dwCount);
  584. sprintf(szJpgPath, "%s\\%s\\%d_%s_%ld.jpg", strSavePath.c_str(), ret ? "abnormal" : "normal", pageNum, id.c_str(), dwCount);
  585. CFile zip;
  586. zip.Open(CA2T(szTxtPath), CFile::modeCreate | CFile::modeWrite);
  587. zip.Write((void*)info.c_str(), info.length());
  588. zip.Close();
  589. cv::Mat cut = src(rc_ansInfo);
  590. ret = cv::imwrite(szJpgPath, cut);
  591. return ret ? 0 : 1;
  592. }
  593. return 0;
  594. }
  595. int PareseModeJson(preinfo::templatesInfo& temeplatInfo)
  596. {
  597. ifstream in("./page.json", ios::binary);
  598. if (!in.is_open())
  599. {
  600. return 1;
  601. }
  602. int uuid = 100000; /// 每个框子的一个独立ID 不会有重复的
  603. Json::Features features;
  604. Json::Reader reader(features);
  605. Json::Value root;
  606. if (!reader.parse(in, root))
  607. {
  608. return 1;
  609. }
  610. if (!root.isObject())
  611. {
  612. return 1;
  613. }
  614. //1.获取模板大小信息
  615. preinfo::PaperTemplateInfo page;
  616. Json::Value imageSize = root["imageSize"];
  617. page.height = imageSize["height"].asInt();
  618. page.width = imageSize["width"].asInt();
  619. //2.获取定位点信息
  620. Json::Value loction = root["location"];
  621. auto funGetPos = [&](Json::Value item) {
  622. preinfo::PaperRect<double> pb;
  623. int x = item["x"].asInt();
  624. int y = item["y"].asInt();
  625. int h = item["height"].asInt();
  626. int w = item["width"].asInt();
  627. pb.centerx = x + w / 2.0;
  628. pb.centery = y + h / 2.0;
  629. pb.width = w;
  630. pb.height = h;
  631. return pb;
  632. };
  633. double offsetx = page.width; double offsety = page.height;
  634. for (int i = 0; i < loction.size(); i++)
  635. {
  636. Json::Value row = loction[i];
  637. preinfo::LocationPoint lc;
  638. lc.id = uuid++;
  639. auto tm = funGetPos(row);
  640. lc.centerx = tm.centerx;
  641. lc.centery = tm.centery;
  642. lc.width = tm.width;
  643. lc.height = tm.height;
  644. if (offsetx > lc.centerx) offsetx = lc.getX();
  645. if (offsety > lc.centery) offsety = lc.getY();
  646. page.vecLocaltionPoints.push_back(lc);
  647. }
  648. //3.获取客观题信息
  649. Json::Value pagenumber = root["pagenumber"];
  650. for (int i = 0; i < pagenumber.size(); i++)
  651. {
  652. Json::Value item = pagenumber[i];
  653. string strId = item["id"].asString();
  654. preinfo::_QuestionChoice _qstc;
  655. _qstc.id = uuid++;
  656. _qstc.vecTiHao.push_back(atoi(strId.c_str()));
  657. double dBoundBox[4] = { 100000,100000,0,0 };
  658. _qstc.type = preinfo::BOX_QUESTION_CHOICE_M;
  659. auto itOpts = item["opt"];
  660. _qstc.number = itOpts.size();
  661. std::vector<preinfo::TtItem> _vctOpt;
  662. for (int i = 0; i < itOpts.size(); i++)
  663. {
  664. preinfo::TtItem opt;
  665. auto tm = funGetPos(itOpts[i]);
  666. opt.centerx = tm.centerx;
  667. opt.centery = tm.centery;
  668. opt.width = tm.width;
  669. opt.height = tm.height;
  670. _qstc.itemSize.width = opt.width;
  671. _qstc.itemSize.height = opt.height;
  672. dBoundBox[0] = dBoundBox[0] > opt.getX() ? opt.getX() : dBoundBox[0];
  673. dBoundBox[1] = dBoundBox[1] > opt.getY() ? opt.getY() : dBoundBox[1];
  674. dBoundBox[2] = dBoundBox[2] < (opt.centerx + opt.width / 2.0) ? (opt.centerx + opt.width / 2.0) : dBoundBox[2];
  675. dBoundBox[3] = dBoundBox[3] < (opt.centery + opt.height / 2.0) ? (opt.centery + opt.height / 2.0) : dBoundBox[3];
  676. auto subItem = itOpts[i];
  677. opt.optName = subItem["optName"].asString();
  678. _vctOpt.push_back(opt);
  679. }
  680. _qstc.width = (dBoundBox[2] - dBoundBox[0]);
  681. _qstc.height = (dBoundBox[3] - dBoundBox[1]);
  682. _qstc.centerx = dBoundBox[0] + _qstc.width / 2.0;
  683. _qstc.centery = dBoundBox[1] + _qstc.height / 2.0;
  684. _qstc.groups = _vctOpt;
  685. page._vecQtChoices.push_back(_qstc);
  686. }
  687. temeplatInfo.push_back(page);
  688. return 0;
  689. }