You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ppocrv5.cpp 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2025 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // pip install paddlepaddle==3.0.0
  4. // pip install paddleocr==3.0.0
  5. // paddlex --install paddle2onnx
  6. // paddleocr ocr -i test.png
  7. // paddlex --paddle2onnx --paddle_model_dir ~/.paddlex/official_models/PP-OCRv5_mobile_det --onnx_model_dir PP-OCRv5_mobile_det
  8. // paddlex --paddle2onnx --paddle_model_dir ~/.paddlex/official_models/PP-OCRv5_mobile_rec --onnx_model_dir PP-OCRv5_mobile_rec
  9. // pnnx PP-OCRv5_mobile_det.onnx inputshape=[1,3,320,320] inputshape2=[1,3,256,256]
  10. // pnnx PP-OCRv5_mobile_rec.onnx inputshape=[1,3,48,160] inputshape2=[1,3,48,256]
  11. // pnnx PP-OCRv5_server_det.onnx inputshape=[1,3,320,320] inputshape2=[1,3,256,256] fp16=0
  12. // pnnx PP-OCRv5_server_rec.onnx inputshape=[1,3,48,160] inputshape2=[1,3,48,256] fp16=0
  13. #include "layer.h"
  14. #include "net.h"
  15. #include <opencv2/core/core.hpp>
  16. #include <opencv2/highgui/highgui.hpp>
  17. #include <opencv2/imgproc/imgproc.hpp>
  18. #include <float.h>
  19. #include <stdio.h>
  20. #include <vector>
  21. #include "ppocrv5_dict.h"
  22. struct Character
  23. {
  24. int id;
  25. float prob;
  26. };
  27. struct Object
  28. {
  29. cv::RotatedRect rrect;
  30. int orientation;
  31. float prob;
  32. std::vector<Character> text;
  33. };
  34. static double contour_score(const cv::Mat& binary, const std::vector<cv::Point>& contour)
  35. {
  36. cv::Rect rect = cv::boundingRect(contour);
  37. if (rect.x < 0)
  38. rect.x = 0;
  39. if (rect.y < 0)
  40. rect.y = 0;
  41. if (rect.x + rect.width > binary.cols)
  42. rect.width = binary.cols - rect.x;
  43. if (rect.y + rect.height > binary.rows)
  44. rect.height = binary.rows - rect.y;
  45. cv::Mat binROI = binary(rect);
  46. cv::Mat mask = cv::Mat::zeros(rect.height, rect.width, CV_8U);
  47. std::vector<cv::Point> roiContour;
  48. for (size_t i = 0; i < contour.size(); i++)
  49. {
  50. cv::Point pt = cv::Point(contour[i].x - rect.x, contour[i].y - rect.y);
  51. roiContour.push_back(pt);
  52. }
  53. std::vector<std::vector<cv::Point> > roiContours = {roiContour};
  54. cv::fillPoly(mask, roiContours, cv::Scalar(255));
  55. double score = cv::mean(binROI, mask).val[0];
  56. return score / 255.f;
  57. }
  58. static cv::Mat get_rotate_crop_image(const cv::Mat& bgr, const Object& object)
  59. {
  60. const int orientation = object.orientation;
  61. const float rw = object.rrect.size.width;
  62. const float rh = object.rrect.size.height;
  63. const int target_height = 48;
  64. const float target_width = rh * target_height / rw;
  65. // warpperspective shall be used to rotate the image
  66. // but actually they are all rectangles, so warpaffine is almost enough :P
  67. cv::Mat dst;
  68. cv::Point2f corners[4];
  69. object.rrect.points(corners);
  70. if (orientation == 0)
  71. {
  72. // horizontal text
  73. // corner points order
  74. // 0--------1
  75. // | |rw -> as angle=90
  76. // 3--------2
  77. // rh
  78. std::vector<cv::Point2f> src_pts(3);
  79. src_pts[0] = corners[0];
  80. src_pts[1] = corners[1];
  81. src_pts[2] = corners[3];
  82. std::vector<cv::Point2f> dst_pts(3);
  83. dst_pts[0] = cv::Point2f(0, 0);
  84. dst_pts[1] = cv::Point2f(target_width, 0);
  85. dst_pts[2] = cv::Point2f(0, target_height);
  86. cv::Mat tm = cv::getAffineTransform(src_pts, dst_pts);
  87. cv::warpAffine(bgr, dst, tm, cv::Size(target_width, target_height), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
  88. }
  89. else
  90. {
  91. // vertial text
  92. // corner points order
  93. // 1----2
  94. // | |
  95. // | |
  96. // | |rh -> as angle=0
  97. // | |
  98. // | |
  99. // 0----3
  100. // rw
  101. std::vector<cv::Point2f> src_pts(3);
  102. src_pts[0] = corners[2];
  103. src_pts[1] = corners[3];
  104. src_pts[2] = corners[1];
  105. std::vector<cv::Point2f> dst_pts(3);
  106. dst_pts[0] = cv::Point2f(0, 0);
  107. dst_pts[1] = cv::Point2f(target_width, 0);
  108. dst_pts[2] = cv::Point2f(0, target_height);
  109. cv::Mat tm = cv::getAffineTransform(src_pts, dst_pts);
  110. cv::warpAffine(bgr, dst, tm, cv::Size(target_width, target_height), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
  111. }
  112. return dst;
  113. }
  114. class PPOCRv5
  115. {
  116. public:
  117. void init();
  118. void detect(const cv::Mat& bgr, std::vector<Object>& objects);
  119. void recognize(const cv::Mat& bgr, Object& object);
  120. protected:
  121. ncnn::Net ppocrv5_det;
  122. ncnn::Net ppocrv5_rec;
  123. };
  124. void PPOCRv5::init()
  125. {
  126. // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
  127. // https://github.com/nihui/ncnn-android-ppocrv5/tree/master/app/src/main/assets
  128. ppocrv5_det.opt.use_vulkan_compute = true;
  129. // ppocrv5_det.opt.use_bf16_storage = true;
  130. // fp16 must be disabled for server model
  131. // ppocrv5_det.opt.use_fp16_packed = false;
  132. // ppocrv5_det.opt.use_fp16_storage = false;
  133. ppocrv5_det.load_param("PP_OCRv5_mobile_det.ncnn.param");
  134. ppocrv5_det.load_model("PP_OCRv5_mobile_det.ncnn.bin");
  135. // ppocrv5_det.load_param("PP_OCRv5_server_det.ncnn.param");
  136. // ppocrv5_det.load_model("PP_OCRv5_server_det.ncnn.bin");
  137. ppocrv5_rec.opt.use_vulkan_compute = true;
  138. // ppocrv5_rec.opt.use_bf16_storage = true;
  139. // fp16 must be disabled for server model
  140. // ppocrv5_rec.opt.use_fp16_packed = false;
  141. // ppocrv5_rec.opt.use_fp16_storage = false;
  142. ppocrv5_rec.load_param("PP_OCRv5_mobile_rec.ncnn.param");
  143. ppocrv5_rec.load_model("PP_OCRv5_mobile_rec.ncnn.bin");
  144. // ppocrv5_rec.load_param("PP_OCRv5_server_rec.ncnn.param");
  145. // ppocrv5_rec.load_model("PP_OCRv5_server_rec.ncnn.bin");
  146. }
  147. void PPOCRv5::detect(const cv::Mat& bgr, std::vector<Object>& objects)
  148. {
  149. const int target_size = 960;
  150. int img_w = bgr.cols;
  151. int img_h = bgr.rows;
  152. const int target_stride = 32;
  153. // letterbox pad to multiple of target_stride
  154. int w = img_w;
  155. int h = img_h;
  156. float scale = 1.f;
  157. if (std::max(w, h) > target_size)
  158. {
  159. if (w > h)
  160. {
  161. scale = (float)target_size / w;
  162. w = target_size;
  163. h = h * scale;
  164. }
  165. else
  166. {
  167. scale = (float)target_size / h;
  168. h = target_size;
  169. w = w * scale;
  170. }
  171. }
  172. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, img_w, img_h, w, h);
  173. int wpad = (w + target_stride - 1) / target_stride * target_stride - w;
  174. int hpad = (h + target_stride - 1) / target_stride * target_stride - h;
  175. ncnn::Mat in_pad;
  176. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  177. const float mean_vals[3] = {0.485f * 255.f, 0.456f * 255.f, 0.406f * 255.f};
  178. const float norm_vals[3] = {1 / 0.229f / 255.f, 1 / 0.224f / 255.f, 1 / 0.225f / 255.f};
  179. in_pad.substract_mean_normalize(mean_vals, norm_vals);
  180. ncnn::Extractor ex = ppocrv5_det.create_extractor();
  181. ex.input("in0", in_pad);
  182. ncnn::Mat out;
  183. ex.extract("out0", out);
  184. const float denorm_vals[1] = {255.f};
  185. out.substract_mean_normalize(0, denorm_vals);
  186. cv::Mat pred(out.h, out.w, CV_8UC1);
  187. out.to_pixels(pred.data, ncnn::Mat::PIXEL_GRAY);
  188. // threshold binary
  189. cv::Mat bitmap;
  190. const float threshold = 0.3f;
  191. cv::threshold(pred, bitmap, threshold * 255, 255, cv::THRESH_BINARY);
  192. // boxes from bitmap
  193. {
  194. // should use dbnet post process, but I think unclip process is difficult to write
  195. // so simply implement expansion. This may lose detection accuracy
  196. // original implementation can be referenced
  197. // https://github.com/MhLiao/DB/blob/master/structure/representers/seg_detector_representer.py
  198. const float box_thresh = 0.6f;
  199. const float enlarge_ratio = 1.95f;
  200. const float min_size = 3 * scale;
  201. const int max_candidates = 1000;
  202. std::vector<std::vector<cv::Point> > contours;
  203. std::vector<cv::Vec4i> hierarchy;
  204. cv::findContours(bitmap, contours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
  205. contours.resize(std::min(contours.size(), (size_t)max_candidates));
  206. for (size_t i = 0; i < contours.size(); i++)
  207. {
  208. const std::vector<cv::Point>& contour = contours[i];
  209. if (contour.size() <= 2)
  210. continue;
  211. double score = contour_score(pred, contour);
  212. if (score < box_thresh)
  213. continue;
  214. cv::RotatedRect rrect = cv::minAreaRect(contour);
  215. float rrect_maxwh = std::max(rrect.size.width, rrect.size.height);
  216. if (rrect_maxwh < min_size)
  217. continue;
  218. int orientation = 0;
  219. if (rrect.angle >= -30 && rrect.angle <= 30 && rrect.size.height > rrect.size.width * 2.7)
  220. {
  221. // vertical text
  222. orientation = 1;
  223. }
  224. if ((rrect.angle <= -60 || rrect.angle >= 60) && rrect.size.width > rrect.size.height * 2.7)
  225. {
  226. // vertical text
  227. orientation = 1;
  228. }
  229. if (rrect.angle < -30)
  230. {
  231. // make orientation from -90 ~ -30 to 90 ~ 150
  232. rrect.angle += 180;
  233. }
  234. if (orientation == 0 && rrect.angle < 30)
  235. {
  236. // make it horizontal
  237. rrect.angle += 90;
  238. std::swap(rrect.size.width, rrect.size.height);
  239. }
  240. if (orientation == 1 && rrect.angle >= 60)
  241. {
  242. // make it vertical
  243. rrect.angle -= 90;
  244. std::swap(rrect.size.width, rrect.size.height);
  245. }
  246. // enlarge
  247. rrect.size.height += rrect.size.width * (enlarge_ratio - 1);
  248. rrect.size.width *= enlarge_ratio;
  249. // adjust offset to original unpadded
  250. rrect.center.x = (rrect.center.x - (wpad / 2)) / scale;
  251. rrect.center.y = (rrect.center.y - (hpad / 2)) / scale;
  252. rrect.size.width = (rrect.size.width) / scale;
  253. rrect.size.height = (rrect.size.height) / scale;
  254. Object obj;
  255. obj.rrect = rrect;
  256. obj.orientation = orientation;
  257. obj.prob = score;
  258. objects.push_back(obj);
  259. }
  260. }
  261. }
  262. void PPOCRv5::recognize(const cv::Mat& bgr, Object& object)
  263. {
  264. cv::Mat roi = get_rotate_crop_image(bgr, object);
  265. ncnn::Mat in = ncnn::Mat::from_pixels(roi.data, ncnn::Mat::PIXEL_BGR, roi.cols, roi.rows);
  266. // ~/.paddlex/official_models/PP-OCRv5_mobile_rec/inference.yml
  267. const float mean_vals[3] = {127.5, 127.5, 127.5};
  268. const float norm_vals[3] = {1.0 / 127.5, 1.0 / 127.5, 1.0 / 127.5};
  269. in.substract_mean_normalize(mean_vals, norm_vals);
  270. ncnn::Extractor ex = ppocrv5_rec.create_extractor();
  271. ex.input("in0", in);
  272. ncnn::Mat out;
  273. ex.extract("out0", out);
  274. // 18385 x len
  275. for (int i = 0; i < out.h; i++)
  276. {
  277. const float* p = out.row(i);
  278. int index = 0;
  279. float max_score = -9999.f;
  280. for (int j = 0; j < out.w; j++)
  281. {
  282. float score = *p++;
  283. if (score > max_score)
  284. {
  285. max_score = score;
  286. index = j;
  287. }
  288. }
  289. if (index <= 0)
  290. continue;
  291. Character ch;
  292. ch.id = index - 1;
  293. ch.prob = max_score;
  294. object.text.push_back(ch);
  295. }
  296. }
  297. static int detect_ppocrv5(const cv::Mat& bgr, std::vector<Object>& objects)
  298. {
  299. PPOCRv5 ppocrv5;
  300. ppocrv5.init();
  301. ppocrv5.detect(bgr, objects);
  302. for (size_t i = 0; i < objects.size(); i++)
  303. {
  304. ppocrv5.recognize(bgr, objects[i]);
  305. }
  306. return 0;
  307. }
  308. static int draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  309. {
  310. static const cv::Scalar colors[] = {
  311. cv::Scalar(156, 39, 176),
  312. cv::Scalar(103, 58, 183),
  313. cv::Scalar(63, 81, 181),
  314. cv::Scalar(33, 150, 243),
  315. cv::Scalar(3, 169, 244),
  316. cv::Scalar(0, 188, 212),
  317. cv::Scalar(0, 150, 136),
  318. cv::Scalar(76, 175, 80),
  319. cv::Scalar(139, 195, 74),
  320. cv::Scalar(205, 220, 57),
  321. cv::Scalar(255, 235, 59),
  322. cv::Scalar(255, 193, 7),
  323. cv::Scalar(255, 152, 0),
  324. cv::Scalar(255, 87, 34),
  325. cv::Scalar(121, 85, 72),
  326. cv::Scalar(158, 158, 158),
  327. cv::Scalar(96, 125, 139)
  328. };
  329. cv::Mat image = bgr.clone();
  330. for (size_t i = 0; i < objects.size(); i++)
  331. {
  332. const Object& obj = objects[i];
  333. const cv::Scalar& color = colors[i % 17];
  334. fprintf(stderr, "%s %.5f at %.2f %.2f %.2f x %.2f @ %.2f = ", obj.orientation == 0 ? "H" : "V", obj.prob,
  335. obj.rrect.center.x, obj.rrect.center.y, obj.rrect.size.width, obj.rrect.size.height, obj.rrect.angle);
  336. cv::Point2f corners[4];
  337. obj.rrect.points(corners);
  338. cv::line(image, corners[0], corners[1], color);
  339. cv::line(image, corners[1], corners[2], color);
  340. cv::line(image, corners[2], corners[3], color);
  341. cv::line(image, corners[3], corners[0], color);
  342. std::string text;
  343. for (size_t j = 0; j < objects[i].text.size(); j++)
  344. {
  345. const Character& ch = objects[i].text[j];
  346. if (ch.id >= character_dict_size)
  347. continue;
  348. text += character_dict[ch.id];
  349. }
  350. fprintf(stderr, "%s\n", text.c_str());
  351. }
  352. fprintf(stderr, "opencv putText can not draw non-latin characters, you may see question marks instead\n");
  353. fprintf(stderr, "see opencv-mobile for drawing non-latin characters\n");
  354. for (size_t i = 0; i < objects.size(); i++)
  355. {
  356. const Object& obj = objects[i];
  357. const cv::Scalar& color = colors[i % 17];
  358. std::string text;
  359. for (size_t j = 0; j < objects[i].text.size(); j++)
  360. {
  361. const Character& ch = objects[i].text[j];
  362. if (ch.id >= character_dict_size)
  363. continue;
  364. if (obj.orientation == 0)
  365. {
  366. text += character_dict[ch.id];
  367. }
  368. else
  369. {
  370. text += character_dict[ch.id];
  371. if (j + 1 < objects[i].text.size())
  372. text += "\n";
  373. }
  374. }
  375. int baseLine = 0;
  376. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  377. int x = obj.rrect.center.x - label_size.width / 2;
  378. int y = obj.rrect.center.y - label_size.height / 2 - baseLine;
  379. if (y < 0)
  380. y = 0;
  381. if (y + label_size.height > image.rows)
  382. y = image.rows - label_size.height;
  383. if (x < 0)
  384. x = 0;
  385. if (x + label_size.width > image.cols)
  386. x = image.cols - label_size.width;
  387. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  388. cv::Scalar(255, 255, 255), -1);
  389. if (obj.orientation == 0)
  390. {
  391. cv::putText(image, text, cv::Point(x, y + label_size.height), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  392. }
  393. else
  394. {
  395. cv::putText(image, text, cv::Point(x, y + label_size.width), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  396. }
  397. }
  398. cv::imshow("image", image);
  399. cv::waitKey(0);
  400. return 0;
  401. }
  402. int main(int argc, char** argv)
  403. {
  404. if (argc != 2)
  405. {
  406. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  407. return -1;
  408. }
  409. const char* imagepath = argv[1];
  410. cv::Mat m = cv::imread(imagepath, 1);
  411. if (m.empty())
  412. {
  413. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  414. return -1;
  415. }
  416. std::vector<Object> objects;
  417. detect_ppocrv5(m, objects);
  418. draw_objects(m, objects);
  419. return 0;
  420. }