lenz_stitcher.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. //
  2. // lenz_stitcher.cpp
  3. // LenzCameraNativeModuleForRN
  4. //
  5. // Created by lr on 2023/2/8.
  6. //
  7. #include "lenz_stitcher.hpp"
  8. Ptr<Feature2D> stitch_feature_finder = SiftFeatureDetector::create();
  9. Ptr<FastFeatureDetector> detector = FastFeatureDetector::create(30);
  10. const string ERROR_PLACE = "PANORAMA_ERROR_PLACE";
  11. // 设定一些全局变量,用于记录后台拼接大图的数据,每次reset的时候需要把这些全局变量也一起重置
  12. Mat big_stitch_image = Mat();
  13. Mat neighbour_homo = Mat();
  14. vector<KeyPoint> neighbour_keypoints;
  15. Mat neighbour_descriptors = Mat();
  16. int big_stitch_status = STITCH_STATUS_INIT;
  17. int big_frame_num = 0;
  18. float big_work_scale = 0;
  19. string big_local_path = "";
  20. inline LenzStitcher::LenzStitcher(string input_path)
  21. {
  22. local_path = input_path;
  23. // 初始化拼接大图时用到的数据
  24. vector<KeyPoint>().swap(neighbour_keypoints);
  25. big_stitch_image = Mat();
  26. neighbour_homo = Mat();
  27. neighbour_descriptors = Mat();
  28. big_stitch_status = STITCH_STATUS_INIT;
  29. big_frame_num = 0;
  30. big_work_scale = 0;
  31. big_local_path = local_path;
  32. // 清理本地目录
  33. if (isFloderexit(local_path.c_str()))
  34. deleteFile(local_path.c_str()); // remove the files and dirs in local path
  35. }
  36. inline float image_resize(Mat &image, Mat &scaled_image, int target_height, int mode)
  37. {
  38. float work_scale = 1.0f;
  39. // will scale down the image size if image rows bigger than max_width
  40. if (mode == 0)
  41. {
  42. if (image.rows > target_height)
  43. work_scale = float(target_height) / float(image.rows);
  44. }
  45. else
  46. {
  47. if (image.cols > target_height)
  48. work_scale = float(target_height) / float(image.cols);
  49. }
  50. resize(image, scaled_image, Size(), work_scale, work_scale, 5);
  51. return work_scale;
  52. }
  53. inline void to_gray(Mat &image, Mat &gray_image)
  54. {
  55. int channels = image.channels();
  56. if (channels == 3) // BGR
  57. cvtColor(image, gray_image, COLOR_BGR2GRAY);
  58. else if (channels == 1) // gray
  59. image.copyTo(gray_image);
  60. }
  61. inline void LenzStitcher::remove_local_path()
  62. {
  63. if (isFloderexit(local_path.c_str()))
  64. {
  65. deleteFile(local_path.c_str()); // remove the files and dirs in local path
  66. rmdir(local_path.c_str()); // remove the local path dir
  67. }
  68. }
  69. /**
  70. * @brief 视频拼接算法,
  71. *
  72. * 输出:
  73. * int数组: [拼接状态,是否需要存图]
  74. * 拼接状态:
  75. * -1: 拍摄完成后拼接大图失败
  76. * 0: 拍摄过程中产生拼接缩略图失败
  77. * 2: 特征点变少,放慢速度
  78. * 3: 特征点极少,即将失败
  79. * 4:当前拍摄固定了方向,请勿往反方向移动
  80. * 是否需要存图:
  81. * 0:不需要
  82. * 1:需要
  83. *
  84. */
  85. inline int *LenzStitcher::ofcheck_stitch(Mat &input_frame, int const direction, int const is_last_one)
  86. {
  87. // cout << "input_frame shape is " << input_frame.rows << "*" << input_frame.rows << ", type is " << input_frame.type();
  88. // 使用光流法来进行图片的匹配
  89. int static stitch_result[2]; // 返回结果有2个字段,第一个字段是拼接状态,第二个字段是是否需要存帧
  90. stitch_result[0] = 1; // 默认当前帧会拼接成功
  91. stitch_result[1] = 0;
  92. if (big_stitch_status == STITCH_STATUS_FAILED)
  93. {
  94. stitch_result[0] = -1; // 拼接大图出现失败,则直接提示失败
  95. return stitch_result;
  96. }
  97. // 最后一帧不计算缩略图直接拼大图并返回大图拼接结果
  98. if (is_last_one)
  99. {
  100. // 在子线程进行拼接
  101. big_frame_index++;
  102. thread t(stitch_big_image, input_frame, last_angles, direction, big_frame_index);
  103. t.detach();
  104. bool stitch_success = get_big_image(big_frame_index);
  105. if (!stitch_success)
  106. {
  107. stitch_result[0] = -1; // 拍摄完成后拼接大图失败
  108. }
  109. return stitch_result;
  110. }
  111. if (stitcher_status == STITCH_STATUS_CHECKING)
  112. {
  113. // cout << "check: The stitcher is still running other function!" << stitcher_status << endl;
  114. stitch_result[0] = 0;
  115. return stitch_result;
  116. }
  117. bool save_this = false;
  118. stitcher_status = STITCH_STATUS_CHECKING;
  119. Mat frame;
  120. float resize_scale = image_resize(input_frame, frame, STITCH_HEIGHT, 1);
  121. // rotate(frame, frame, 0);
  122. // 图片压缩
  123. Mat scaled_frame, scaled_gray_frame;
  124. resize_scale = image_resize(input_frame, scaled_frame, FEATURE_HEIGHT, 1);
  125. // rotate(scaled_frame, scaled_frame, 0);
  126. to_gray(scaled_frame, scaled_gray_frame);
  127. scaled_frame.release();
  128. float work_scale = 1.0 * scaled_gray_frame.rows / frame.rows;
  129. vector<KeyPoint> frame_keypoints;
  130. detector->detect(scaled_gray_frame, frame_keypoints);
  131. if (frame_keypoints.size() < matches_thresh)
  132. {
  133. stitch_result[0] = 0;
  134. stitcher_status = STITCH_STATUS_FREE;
  135. return stitch_result;
  136. }
  137. frame_index++;
  138. // get the perspective corners
  139. vector<Point2f> frame_corners(4);
  140. frame_corners[0] = Point2f(0, 0);
  141. frame_corners[1] = Point2f(frame.cols, 0);
  142. frame_corners[2] = Point2f(frame.cols, frame.rows);
  143. frame_corners[3] = Point2f(0, frame.rows);
  144. vector<Point2f> transpose_corners(4);
  145. if (frame_index == 1)
  146. {
  147. last_stitch_image = frame;
  148. // update the last stitch image
  149. // string _stitched_img_path = local_path + "last_stitch.jpg";
  150. // bool status = imwrite(_stitched_img_path, frame);
  151. // last_stitch_image_path = _stitched_img_path;
  152. last_warp_points = frame_corners;
  153. last_check_data.scaled_gray_frame = scaled_gray_frame;
  154. last_check_data.keypoints = frame_keypoints;
  155. last_check_data.work_scale = work_scale;
  156. last_check_data.homo = (Mat_<double>(3, 3) << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
  157. // 在子线程进行拼接
  158. big_frame_index++;
  159. thread t(stitch_big_image, input_frame, last_angles, direction, big_frame_index);
  160. t.detach();
  161. stitcher_status = STITCH_STATUS_FREE;
  162. stitch_result[1] = 1;
  163. return stitch_result;
  164. }
  165. vector<Point2f> frame_points, last_frame_points;
  166. randomSelectKeyPoints(last_check_data.keypoints, last_frame_points, 250);
  167. vector<uchar> vstatus;
  168. vector<float> verror;
  169. calcOpticalFlowPyrLK(last_check_data.scaled_gray_frame, scaled_gray_frame, last_frame_points, frame_points, vstatus, verror);
  170. vector<Point2f> matched_frame_points, neighbour_points;
  171. int good_match_count = 0;
  172. for (unsigned int i = 0; i < vstatus.size(); i++)
  173. {
  174. if (vstatus[i] == 0)
  175. continue;
  176. good_match_count++;
  177. neighbour_points.push_back(Point2f(last_frame_points[i].x / work_scale, last_frame_points[i].y / work_scale));
  178. matched_frame_points.push_back(Point2f(frame_points[i].x / work_scale, frame_points[i].y / work_scale));
  179. }
  180. // LOGI("matched_frame_points size %d", matched_frame_points.size());
  181. if (matched_frame_points.size() < matches_thresh)
  182. {
  183. stitcher_status = STITCH_STATUS_FREE;
  184. failed_count++;
  185. if (failed_count >= failed_thresh)
  186. {
  187. stitch_result[0] = 0; // 特征点太少导致缩略图拼接失败了
  188. }
  189. return stitch_result;
  190. }
  191. Mat H = findHomography(matched_frame_points, neighbour_points, RANSAC); // find current frame perspective to neighbour image homography
  192. // get the initial perspective corners, to find the shift
  193. perspectiveTransform(frame_corners, transpose_corners, H);
  194. int move_direction = get_direction(frame_corners, transpose_corners); // 1从上到下,2从下到上,3从左到右,4从右到左
  195. if (last_direction == 0)
  196. {
  197. last_direction = move_direction; // 异形拼接的时候会拐弯,所以需要记录下它的上一个方向,当方向变化时,需要把那一帧给拼起来
  198. }
  199. if ((direction == 1 && move_direction == 2) ||
  200. (direction == 2 && move_direction == 1) ||
  201. (direction == 3 && move_direction == 4) ||
  202. (direction == 4 && move_direction == 3))
  203. {
  204. // LOGI("请保持手机稳定向固定方向移动!");
  205. stitcher_status = STITCH_STATUS_FREE;
  206. stitch_result[0] = 4;
  207. return stitch_result;
  208. }
  209. H = last_check_data.homo * H;
  210. perspectiveTransform(frame_corners, transpose_corners, H);
  211. float left_x, right_x, top_y, bottom_y;
  212. left_x = min_axis(vector<float>{transpose_corners[0].x, transpose_corners[1].x, transpose_corners[2].x, transpose_corners[3].x});
  213. top_y = min_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y, transpose_corners[2].y, transpose_corners[3].y});
  214. float base_shift_x = (left_x < 0) ? -left_x : 0;
  215. total_shift_x += base_shift_x;
  216. float base_shift_y = (top_y < 0) ? -top_y : 0;
  217. total_shift_y += base_shift_y;
  218. Mat shift = (Mat_<double>(3, 3) << 1.0, 0.0, base_shift_x, 0.0, 1.0, base_shift_y, 0.0, 0.0, 1.0);
  219. H = shift * H;
  220. perspectiveTransform(last_warp_points, last_warp_points, shift); // 把之前的需要存下来的图的框映射到拼接图上
  221. perspectiveTransform(frame_corners, transpose_corners, H); // 把当前图片的四个顶点映射到拼接图上
  222. // 如果图片映射后的4个顶点非凸,直接返回失败
  223. if (!is_convex(transpose_corners))
  224. {
  225. // LOGE("error conners is not convex");
  226. stitcher_status = STITCH_STATUS_FREE;
  227. failed_count++;
  228. if (failed_count >= failed_thresh)
  229. {
  230. stitch_result[0] = 0;
  231. }
  232. return stitch_result;
  233. }
  234. // 计算映射后的四边形的四个内角
  235. float a0 = angle_of_two_vector(transpose_corners[1], transpose_corners[3], transpose_corners[0]);
  236. float a1 = angle_of_two_vector(transpose_corners[2], transpose_corners[0], transpose_corners[1]);
  237. float a2 = angle_of_two_vector(transpose_corners[3], transpose_corners[1], transpose_corners[2]);
  238. float a3 = angle_of_two_vector(transpose_corners[0], transpose_corners[2], transpose_corners[3]);
  239. // LOGI("calced angle a0 %f, a1 %f, a2 %f a3 %f", a0, a1, a2, a3);
  240. vector<float> angles = vector<float>{a0, a1, a2, a3};
  241. float min_angle = min_axis(angles);
  242. // 获取4个映射到拼接图外接顶点
  243. left_x = min_axis(vector<float>{transpose_corners[0].x, transpose_corners[3].x});
  244. right_x = max_axis(vector<float>{transpose_corners[1].x, transpose_corners[2].x});
  245. bottom_y = max_axis(vector<float>{transpose_corners[2].y, transpose_corners[3].y});
  246. top_y = min_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y});
  247. // 获取拼接图的尺寸
  248. float stitch_width = MAX(right_x, last_stitch_image.cols + total_shift_x);
  249. float stitch_height = MAX(bottom_y, last_stitch_image.rows + total_shift_y);
  250. float warp_width = right_x - left_x;
  251. float warp_height = bottom_y - top_y;
  252. // 判断一些异常情况要及时返回失败
  253. if (min_angle < angle_thresh || stitch_width > MAX_SIZE || stitch_height > MAX_SIZE || warp_width < 2 || warp_height < 2)
  254. {
  255. // LOGE("error angle %f, stitch shape %f*%f, warp shape %f*%f", angle, stitch_width, stitch_height, warp_width, warp_height);
  256. stitcher_status = STITCH_STATUS_FREE;
  257. failed_count++;
  258. if (failed_count >= failed_thresh)
  259. {
  260. stitch_result[0] = 0;
  261. }
  262. return stitch_result;
  263. }
  264. last_angles = angles;
  265. // 计算当前图和上一个保存下来的图在拼接图上的重合度
  266. float iou = single_box_iou(last_warp_points, transpose_corners);
  267. // 如果当前图片与上一张存下来的图的iou低于阈值或者传入参数告诉我这是最后一帧
  268. // 或者手机移动的方向变化了(设定一下iou的阈值排除抖动的干扰)
  269. if (iou < iou_thresh || (last_direction != move_direction && iou < 0.9))
  270. {
  271. last_warp_points = transpose_corners;
  272. stitch_result[1] = 1; // 需要保存当前帧到本地
  273. // 在子线程进行拼接
  274. big_frame_index++;
  275. save_this = true;
  276. thread t(stitch_big_image, input_frame, angles, direction, big_frame_index);
  277. t.detach();
  278. }
  279. // 开始拼接,设定拼接频率
  280. if (save_this)
  281. {
  282. // merge the warped frame to the last stitched image
  283. Mat stitch_image(stitch_height, stitch_width, CV_8UC3, Scalar(0));
  284. // copy last stitch image to this new image
  285. last_stitch_image.copyTo(stitch_image(Rect(total_shift_x, total_shift_y, last_stitch_image.cols, last_stitch_image.rows)));
  286. total_shift_x = 0;
  287. total_shift_y = 0;
  288. Mat warpH = H.clone();
  289. Mat warp_shift = (Mat_<double>(3, 3) << 1.0, 0.0, -left_x, 0.0, 1.0, -top_y, 0.0, 0.0, 1.0);
  290. warpH = warp_shift * warpH;
  291. Mat scaled_image_warp;
  292. warpPerspective(frame, scaled_image_warp, warpH, Size(warp_width, warp_height));
  293. Mat last_shift_img = stitch_image.clone();
  294. scaled_image_warp.copyTo(stitch_image(Rect(left_x, top_y, warp_width, warp_height)));
  295. scaled_image_warp.release();
  296. optimizeSeam(last_shift_img, stitch_image, transpose_corners);
  297. last_shift_img.release();
  298. // string _stitched_img_path = local_path + "last_stitch.jpg";
  299. // bool status = imwrite(_stitched_img_path, stitch_image);
  300. // last_stitch_image_path = _stitched_img_path;
  301. last_stitch_image = stitch_image;
  302. }
  303. last_check_data.scaled_gray_frame = scaled_gray_frame;
  304. last_check_data.keypoints = frame_keypoints;
  305. last_check_data.work_scale = work_scale;
  306. last_check_data.homo = H;
  307. last_direction = move_direction;
  308. stitcher_status = STITCH_STATUS_FREE;
  309. int point_size = MIN(frame_keypoints.size(), matched_frame_points.size());
  310. if (point_size < 20)
  311. {
  312. stitch_result[0] = 3; // 特征点极少,即将失败
  313. }
  314. else if (point_size < 100)
  315. {
  316. stitch_result[0] = 2; // 特征点变少,放慢速度
  317. }
  318. failed_count = 0; // 当前帧拼接成功的话重置拼接失败的次数
  319. return stitch_result;
  320. }
  321. inline void stitch_big_image(Mat frame, vector<float> angles, int direction, int big_frame_index)
  322. {
  323. double start, finish;
  324. // 如果前面某张图片拼接大图的时候失败了,后续也不用继续拼了
  325. if (big_stitch_status == STITCH_STATUS_FAILED)
  326. {
  327. // LOGE("sub thread: stitch failed %d", big_frame_index);
  328. big_frame_num++;
  329. return;
  330. }
  331. try
  332. {
  333. float resize_scale = image_resize(frame, frame, BIG_STITCH_HEIGHT, 1);
  334. rotate(frame, frame, 0);
  335. // 只有在按照固定方向拼接的时候才进行柱面投影,否则接缝会太多不好看,
  336. // 角度变化太大的话对输入图片加入柱面投影以确保拼接图不会变形太大
  337. float angle1 = (angles[0] + angles[3]) / 2, angle2 = (angles[1] + angles[2]) / 2;
  338. if (angle1 < 80)
  339. {
  340. cylindrical_projection(frame, frame, angle1);
  341. }
  342. else if (angle2 < 80)
  343. {
  344. cylindrical_projection(frame, frame, angle2);
  345. }
  346. Mat scaled_frame;
  347. big_work_scale = image_resize(frame, scaled_frame, BIG_FEATURE_HEIGHT, 0);
  348. vector<KeyPoint> keypoints;
  349. Mat descriptors;
  350. stitch_feature_finder->detectAndCompute(scaled_frame, Mat(), keypoints, descriptors);
  351. // test
  352. string _img_path = big_local_path + "big_frame" + to_string(big_frame_index) + ".jpg";
  353. bool status = imwrite(_img_path, scaled_frame);
  354. test_image_path = _img_path;
  355. start = static_cast<double>(getTickCount());
  356. while (big_stitch_status == STITCH_STATUS_STITCHING)
  357. {
  358. finish = static_cast<double>(getTickCount());
  359. if ((finish - start) / getTickFrequency() > 10)
  360. {
  361. // LOGE("sub thread: failed cause stitching long time %d", big_frame_index);
  362. big_frame_num++;
  363. big_stitch_status = STITCH_STATUS_FAILED;
  364. return;
  365. }
  366. usleep(10000); // 等待10ms, 其他线程正在拼接,等待其他线程结束
  367. }
  368. start = static_cast<double>(getTickCount());
  369. while (big_frame_index != big_frame_num + 1)
  370. {
  371. finish = static_cast<double>(getTickCount());
  372. if ((finish - start) / getTickFrequency() > 10)
  373. {
  374. // LOGE("sub thread: failed cause wait long time %d", big_frame_index);
  375. big_frame_num++;
  376. big_stitch_status = STITCH_STATUS_FAILED;
  377. return;
  378. }
  379. usleep(10000); // 等待10ms, 排队,按顺序拼
  380. }
  381. if (big_stitch_status == STITCH_STATUS_INIT) // 第一张图
  382. {
  383. big_stitch_status = STITCH_STATUS_STITCHING;
  384. big_stitch_image = frame;
  385. neighbour_homo = (Mat_<double>(3, 3) << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
  386. neighbour_keypoints = keypoints;
  387. neighbour_descriptors = descriptors;
  388. big_stitch_status = STITCH_STATUS_FREE;
  389. // LOGI("sub thread: stitch finished %d", big_frame_index);
  390. big_frame_num++;
  391. return;
  392. }
  393. // 正式开始拼接
  394. big_stitch_status = STITCH_STATUS_STITCHING;
  395. // LOGI("sub thread: start stitching %d", big_frame_index);
  396. vector<DMatch> good_matches;
  397. single_match(neighbour_descriptors, descriptors, good_matches, 0.2);
  398. int good_match_count = good_matches.size();
  399. if (good_match_count < 20)
  400. {
  401. // LOGE("sub thread: stitch %d image failed, too less good match point %d", big_frame_index, good_match_count);
  402. big_stitch_status = STITCH_STATUS_FAILED;
  403. big_frame_num++;
  404. return;
  405. }
  406. vector<Point2f> frame_points, neighbour_points;
  407. Point2f neighbour_point, frame_point;
  408. for (int i = 0; i < good_match_count; i++)
  409. {
  410. // Get the keypoints from the good matches
  411. frame_point = keypoints[good_matches[i].trainIdx].pt;
  412. frame_point.x = frame_point.x / big_work_scale; // 把点的位置映射回需要拼接的大图上
  413. frame_point.y = frame_point.y / big_work_scale;
  414. frame_points.push_back(frame_point);
  415. neighbour_point = neighbour_keypoints[good_matches[i].queryIdx].pt;
  416. neighbour_point.x = neighbour_point.x / big_work_scale;
  417. neighbour_point.y = neighbour_point.y / big_work_scale;
  418. neighbour_points.push_back(neighbour_point);
  419. }
  420. Mat H;
  421. H = findHomography(frame_points, neighbour_points, RANSAC); // find current frame perspective to neighbour image homography
  422. if (H.empty())
  423. {
  424. // LOGE("sub thread: stitch %d image failed, H is empty", big_frame_index);
  425. big_stitch_status = STITCH_STATUS_FAILED;
  426. big_frame_num++;
  427. return;
  428. }
  429. H = neighbour_homo * H;
  430. vector<Point2f> frame_corners(4), transpose_corners(4);
  431. frame_corners[0] = Point2f(0, 0);
  432. frame_corners[1] = Point2f(frame.cols, 0);
  433. frame_corners[2] = Point2f(frame.cols, frame.rows);
  434. frame_corners[3] = Point2f(0, frame.rows);
  435. perspectiveTransform(frame_corners, transpose_corners, H);
  436. if (!is_convex(transpose_corners))
  437. {
  438. // LOGE("sub thread: stitch %d image failed, calced corners is not convex", big_frame_index);
  439. big_stitch_status = STITCH_STATUS_FAILED;
  440. big_frame_num++;
  441. return;
  442. }
  443. float left_x, right_x, top_y, bottom_y;
  444. left_x = min_axis(vector<float>{transpose_corners[0].x, transpose_corners[1].x, transpose_corners[2].x, transpose_corners[3].x});
  445. top_y = min_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y, transpose_corners[2].y, transpose_corners[3].y});
  446. float base_shift_x = (left_x < 0) ? -left_x : 0;
  447. float base_shift_y = (top_y < 0) ? -top_y : 0;
  448. Mat shift = (Mat_<double>(3, 3) << 1.0, 0.0, base_shift_x, 0.0, 1.0, base_shift_y, 0.0, 0.0, 1.0);
  449. H = shift * H;
  450. perspectiveTransform(frame_corners, transpose_corners, H);
  451. left_x = min_axis(vector<float>{transpose_corners[0].x, transpose_corners[1].x, transpose_corners[2].x, transpose_corners[3].x});
  452. right_x = max_axis(vector<float>{transpose_corners[0].x, transpose_corners[1].x, transpose_corners[2].x, transpose_corners[3].x});
  453. bottom_y = max_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y, transpose_corners[2].y, transpose_corners[3].y});
  454. top_y = min_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y, transpose_corners[2].y, transpose_corners[3].y});
  455. float stitch_width = MAX(right_x, big_stitch_image.cols + base_shift_x);
  456. float stitch_height = MAX(bottom_y, big_stitch_image.rows + base_shift_y);
  457. if (stitch_width > BIG_MAX_SIZE || stitch_height > BIG_MAX_SIZE)
  458. {
  459. // LOGE("sub thread: stitch %d image failed, TOO BIG", big_frame_index);
  460. big_stitch_status = STITCH_STATUS_FAILED;
  461. big_frame_num++;
  462. return;
  463. }
  464. float warp_width = right_x - left_x;
  465. float warp_height = bottom_y - top_y;
  466. Mat stitch_image(stitch_height, stitch_width, CV_8UC3, Scalar(0));
  467. // 把上一张拼接图贴到对应的区域
  468. big_stitch_image.copyTo(stitch_image(Rect(base_shift_x, base_shift_y, big_stitch_image.cols, big_stitch_image.rows)));
  469. // 截取出上一张拼接图在当前图片映射的区域的矩形,获取它在这个矩形内的轮廓
  470. Mat shift_stitch_image = stitch_image(Rect(left_x, top_y, warp_width, warp_height));
  471. Mat tmp_gray, tmp_binary;
  472. cvtColor(shift_stitch_image, tmp_gray, COLOR_BGR2GRAY);
  473. threshold(tmp_gray, tmp_binary, 1, 255, THRESH_BINARY);
  474. tmp_gray.release();
  475. vector<vector<Point>> contours;
  476. vector<Vec4i> hierarchy;
  477. findContours(tmp_binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
  478. tmp_binary.release();
  479. // 只留下最大的那个contours
  480. int _max_count = 0;
  481. int _max_idx = 0;
  482. for (int _i = 0; _i < contours.size(); _i++)
  483. {
  484. int point_num = contours[_i].size();
  485. if (point_num > _max_count)
  486. {
  487. _max_count = point_num;
  488. _max_idx = _i;
  489. }
  490. }
  491. contours = vector<vector<Point>>{contours[_max_idx]};
  492. // 对图片映射的区域扣掉上与一张图重合的部分后再直接相加融合,然后再处理接缝
  493. Mat shift_frame_warp;
  494. Mat warpH = H.clone();
  495. Mat warp_shift = (Mat_<double>(3, 3) << 1.0, 0.0, -left_x, 0.0, 1.0, -top_y, 0.0, 0.0, 1.0);
  496. warpH = warp_shift * warpH;
  497. warpPerspective(frame, shift_frame_warp, warpH, Size(warp_width, warp_height));
  498. Mat tmp_shifted_frame_warp = shift_frame_warp.clone();
  499. fillPoly(shift_frame_warp, contours, Scalar(0));
  500. shift_stitch_image = shift_stitch_image + shift_frame_warp;
  501. fill_contours(contours, tmp_shifted_frame_warp, shift_stitch_image);
  502. // 拼接好的图贴到对应的矩形区域
  503. shift_stitch_image.copyTo(stitch_image(Rect(left_x, top_y, warp_width, warp_height)));
  504. // 更新数据用于下次拼接
  505. big_stitch_image = stitch_image;
  506. neighbour_homo = H;
  507. neighbour_keypoints = keypoints;
  508. neighbour_descriptors = descriptors;
  509. big_stitch_status = STITCH_STATUS_FREE;
  510. big_frame_num++;
  511. }
  512. catch (const std::exception &e)
  513. {
  514. // 如果遇到了未捕获的异常,打印失败的信息之后直接返回失败。所有失败的情况尽可能在上面的代码里都处理掉,不要在这里处理
  515. // LOGE("sub thread: when stitching %d big image encounter an error: %s", big_frame_index, e.what());
  516. big_stitch_status = STITCH_STATUS_FAILED;
  517. big_frame_num++;
  518. }
  519. }
  520. bool LenzStitcher::get_big_image(int big_frame_index)
  521. {
  522. double start = static_cast<double>(getTickCount());
  523. if (big_stitch_status == STITCH_STATUS_FAILED)
  524. {
  525. return false;
  526. }
  527. double finish;
  528. while (big_frame_index > big_frame_num)
  529. {
  530. finish = static_cast<double>(getTickCount());
  531. if ((finish - start) / getTickFrequency() > 10)
  532. {
  533. break; // 等待了10秒都还没有拼完,则直接返回失败, 无论什么情况下,都不该等那么久
  534. }
  535. usleep(10000); // 还在拼接中,继续等待拼接结束
  536. }
  537. if (big_frame_index == big_frame_num && big_stitch_status == STITCH_STATUS_FREE) // 全部都拼接完成了,将最后的图片保存到本地并记录路径
  538. {
  539. string _img_path = big_local_path + "big_stitch.jpg";
  540. bool status = imwrite(_img_path, big_stitch_image);
  541. big_stitch_image_path = _img_path;
  542. }
  543. // LOGI("finish stitching big image...");
  544. return true;
  545. }
  546. inline bool is_good_green_box(const vector<Point2f> &corners, const Mat &cpu_frame, float area_thresh, float angle_thresh)
  547. {
  548. vector<Point> contour;
  549. for (int p_idx = 0; p_idx < corners.size(); p_idx++)
  550. contour.push_back(Point((int)corners[p_idx].x, (int)corners[p_idx].y));
  551. if (!isContourConvex(contour))
  552. {
  553. // LOGE("check: the frame is not convex!");
  554. return false;
  555. }
  556. float angle = calc_hangle(corners);
  557. // LOGI("check: the perspective angle is %lf", angle);
  558. if (angle > angle_thresh)
  559. {
  560. // LOGE("check: the perspective angle is %lf, too large!", angle);
  561. return false;
  562. }
  563. float frame_area = 1.0 * cpu_frame.cols * cpu_frame.rows;
  564. float green_box_area;
  565. Mat mask;
  566. mask = Mat::zeros(cpu_frame.size(), CV_8UC1);
  567. fillPoly(mask, vector<vector<Point>>{contour}, Scalar(1));
  568. green_box_area = countNonZero(mask);
  569. float area_p = green_box_area / frame_area;
  570. // LOGI("check: the green box area p is %f", area_p);
  571. if (area_p < area_thresh)
  572. {
  573. // LOGE("check: the frame is too small!");
  574. return false;
  575. }
  576. return true;
  577. }
  578. inline float calc_area(const vector<Point2f> &corners, const Mat &frame)
  579. {
  580. vector<Point> contour;
  581. for (int p_idx = 0; p_idx < corners.size(); p_idx++)
  582. contour.push_back(Point(corners[p_idx].x, corners[p_idx].y));
  583. if (!isContourConvex(contour))
  584. {
  585. // LOGE("check: the frame is not convex!");
  586. return 0;
  587. }
  588. float frame_area = 1.0 * frame.cols * frame.rows;
  589. float green_box_area;
  590. Mat mask;
  591. mask = Mat::zeros(frame.size(), CV_8UC1);
  592. fillPoly(mask, vector<vector<Point>>{contour}, Scalar(1));
  593. green_box_area = countNonZero(mask);
  594. float area_p = green_box_area / frame_area;
  595. return area_p;
  596. }
  597. inline bool is_convex(const vector<Point2f> &corners)
  598. {
  599. vector<Point2f> contour;
  600. for (int p_idx = 0; p_idx < corners.size(); p_idx++)
  601. contour.push_back(Point2f(corners[p_idx].x, corners[p_idx].y));
  602. if (isContourConvex(contour))
  603. return true;
  604. return false;
  605. }
  606. inline float min_axis(vector<float> input_list)
  607. {
  608. float min_value = input_list[0];
  609. for (int i = 1; i < input_list.size(); i++)
  610. if (min_value > input_list[i])
  611. min_value = input_list[i];
  612. return min_value;
  613. }
  614. inline float max_axis(vector<float> input_list)
  615. {
  616. float max_value = input_list[0];
  617. for (int i = 1; i < input_list.size(); i++)
  618. if (max_value < input_list[i])
  619. max_value = input_list[i];
  620. return max_value;
  621. }
  622. // 计算四边形的四个角
  623. void calc_angles(vector<Point2f> &conners)
  624. {
  625. float a0 = angle_of_two_vector(conners[1], conners[3], conners[0]);
  626. float a1 = angle_of_two_vector(conners[2], conners[0], conners[1]);
  627. float a2 = angle_of_two_vector(conners[3], conners[1], conners[2]);
  628. float a3 = angle_of_two_vector(conners[0], conners[2], conners[3]);
  629. // LOGI("calced angle a0 %f, a1 %f, a2 %f a3 %f", a0, a1, a2, a3);
  630. }
  631. // 以pt1为M点 pt2为N点 c为O点
  632. float angle_of_two_vector(Point2f &pt1, Point2f &pt2, Point2f &c)
  633. {
  634. float theta = atan2(pt1.x - c.x, pt1.y - c.y) - atan2(pt2.x - c.x, pt2.y - c.y);
  635. if (theta > M_PI)
  636. {
  637. theta -= 2 * M_PI;
  638. }
  639. if (theta < -M_PI)
  640. {
  641. theta += 2 * M_PI;
  642. }
  643. theta = theta * 180.0 / M_PI;
  644. return theta;
  645. }
  646. inline float calc_hangle(const vector<cv::Point2f> &conners)
  647. {
  648. float angle = 0.0f;
  649. float angle1 = abs(atan((conners[0].y - conners[1].y) / (conners[0].x - conners[1].x))) * 180.0 / M_PI;
  650. float angle2 = abs(atan((conners[2].y - conners[3].y) / (conners[2].x - conners[3].x))) * 180.0 / M_PI;
  651. angle = (angle2 > angle1) ? angle2 : angle1;
  652. return angle;
  653. }
  654. inline float calc_vangle(const vector<cv::Point2f> &conners)
  655. {
  656. float angle = 0.0f;
  657. float angle1 = abs(atan((conners[0].y - conners[3].y) / (conners[0].x - conners[3].x))) * 180.0 / M_PI;
  658. float angle2 = abs(atan((conners[1].y - conners[2].y) / (conners[1].x - conners[2].x))) * 180.0 / M_PI;
  659. // LOGI("ofchcek: vertical angle1 %f, angle2 %f", angle1, angle2);
  660. angle = (angle2 > angle1) ? angle2 : angle1;
  661. return 90 - angle;
  662. }
  663. float calc_angle(const vector<cv::Point2f> &conners)
  664. {
  665. float angle = 0.0f;
  666. float angle1 = abs(atan((conners[0].y - conners[1].y) / (conners[0].x - conners[1].x))) * 180.0 / M_PI;
  667. float angle2 = abs(atan((conners[2].y - conners[3].y) / (conners[2].x - conners[3].x))) * 180.0 / M_PI;
  668. // LOGI("ofchcek: horizontal angle1 %f, angle2 %f", angle1, angle2);
  669. angle = (angle2 > angle1) ? angle2 : angle1;
  670. angle1 = abs(atan((conners[0].y - conners[3].y) / (conners[0].x - conners[3].x))) * 180.0 / M_PI;
  671. angle2 = abs(atan((conners[1].y - conners[2].y) / (conners[1].x - conners[2].x))) * 180.0 / M_PI;
  672. // LOGI("ofchcek: vertical angle1 %f, angle2 %f", angle1, angle2);
  673. return angle;
  674. }
  675. inline void double_match(const Mat &query_des, const Mat &train_des, vector<DMatch> &good_matches, float check_match_conf)
  676. {
  677. // BFMatcher matcher(NORM_L2);
  678. FlannBasedMatcher matcher;
  679. set<pair<int, int>> match_indices;
  680. vector<vector<DMatch>> matches;
  681. matcher.knnMatch(query_des, train_des, matches, 2);
  682. for (size_t i = 0; i < matches.size(); ++i)
  683. {
  684. if (matches[i].size() < 2)
  685. continue;
  686. const DMatch &m0 = matches[i][0];
  687. const DMatch &m1 = matches[i][1];
  688. if (m0.distance < (1 - check_match_conf) * m1.distance)
  689. {
  690. good_matches.push_back(m0);
  691. match_indices.insert(make_pair(m0.queryIdx, m0.trainIdx));
  692. }
  693. }
  694. matches.clear();
  695. matcher.knnMatch(train_des, query_des, matches, 2);
  696. for (size_t i = 0; i < matches.size(); ++i)
  697. {
  698. if (matches[i].size() < 2)
  699. continue;
  700. const DMatch &m0 = matches[i][0];
  701. const DMatch &m1 = matches[i][1];
  702. if (m0.distance < (1 - check_match_conf) * m1.distance)
  703. if (match_indices.find(make_pair(m0.trainIdx, m0.queryIdx)) == match_indices.end())
  704. good_matches.push_back(DMatch(m0.trainIdx, m0.queryIdx, m0.distance));
  705. }
  706. }
  707. inline void single_match(const Mat &query_des, const Mat &train_des, vector<DMatch> &good_matches, float check_match_conf)
  708. {
  709. // BFMatcher matcher(NORM_L2);
  710. FlannBasedMatcher matcher;
  711. vector<vector<DMatch>> matches;
  712. matcher.knnMatch(query_des, train_des, matches, 2);
  713. for (size_t i = 0; i < matches.size(); ++i)
  714. {
  715. if (matches[i].size() < 2)
  716. continue;
  717. const DMatch &m0 = matches[i][0];
  718. const DMatch &m1 = matches[i][1];
  719. if (m0.distance < (1 - check_match_conf) * m1.distance)
  720. good_matches.push_back(m0);
  721. }
  722. }
  723. inline void getFilePath(const char *path, const char *filename, char *filepath)
  724. {
  725. strcpy(filepath, path);
  726. if (filepath[strlen(path) - 1] != '/')
  727. strcat(filepath, "/");
  728. strcat(filepath, filename);
  729. }
  730. inline void deleteFile(const char *path)
  731. {
  732. DIR *dir;
  733. struct dirent *dirinfo;
  734. struct stat statbuf;
  735. char filepath[256] = {0};
  736. lstat(path, &statbuf);
  737. if (S_ISREG(statbuf.st_mode)) // 判断是否是常规文件
  738. {
  739. remove(path);
  740. }
  741. else if (S_ISDIR(statbuf.st_mode)) // 判断是否是目录
  742. {
  743. if ((dir = opendir(path)) == NULL)
  744. return;
  745. while ((dirinfo = readdir(dir)) != NULL)
  746. {
  747. getFilePath(path, dirinfo->d_name, filepath);
  748. if (strcmp(dirinfo->d_name, ".") == 0 || strcmp(dirinfo->d_name, "..") == 0) // 判断是否是特殊目录
  749. continue;
  750. deleteFile(filepath);
  751. rmdir(filepath);
  752. // LOGI("delete: remove local file %s successfully", filepath);
  753. }
  754. closedir(dir);
  755. }
  756. return;
  757. }
  758. inline bool isFloderexit(const char *path)
  759. {
  760. DIR *dp;
  761. if ((dp = opendir(path)) == NULL)
  762. {
  763. return false;
  764. }
  765. closedir(dp);
  766. return true;
  767. }
  768. // 为了避免光流算法耗时太长,限定特征点的最大的个数
  769. void randomSelectKeyPoints(vector<KeyPoint> kpts, vector<Point2f> &pts, int max_num)
  770. {
  771. random_device rd;
  772. mt19937 rng(rd());
  773. shuffle(kpts.begin(), kpts.end(), rng);
  774. for (int i = 0; i < kpts.size(); i++)
  775. {
  776. if (i >= max_num)
  777. continue;
  778. pts.push_back(kpts[i].pt);
  779. }
  780. return;
  781. }
  782. // 优化两图的接缝处,使得拼接自然
  783. inline void optimizeSeam(Mat &last_img, Mat &stitched_image, vector<Point2f> &transpose_corners)
  784. {
  785. int thresh = 10;
  786. // 获取4个映射到大拼接图后的顶点
  787. int left_x = (int)min_axis(vector<float>{transpose_corners[0].x, transpose_corners[1].x, transpose_corners[2].x, transpose_corners[3].x});
  788. int right_x = (int)max_axis(vector<float>{transpose_corners[0].x, transpose_corners[1].x, transpose_corners[2].x, transpose_corners[3].x});
  789. int bottom_y = (int)max_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y, transpose_corners[2].y, transpose_corners[3].y});
  790. int top_y = (int)min_axis(vector<float>{transpose_corners[0].y, transpose_corners[1].y, transpose_corners[2].y, transpose_corners[3].y});
  791. LinePara lp0, lp1, lp2, lp3;
  792. float k20, k21, k22, k23;
  793. getLinePara(transpose_corners[0].x, transpose_corners[0].y, transpose_corners[1].x, transpose_corners[1].y, lp0);
  794. k20 = sqrt(lp0.k * lp0.k + 1);
  795. getLinePara(transpose_corners[1].x, transpose_corners[1].y, transpose_corners[2].x, transpose_corners[2].y, lp1);
  796. k21 = sqrt(lp1.k * lp1.k + 1);
  797. getLinePara(transpose_corners[2].x, transpose_corners[2].y, transpose_corners[3].x, transpose_corners[3].y, lp2);
  798. k22 = sqrt(lp2.k * lp2.k + 1);
  799. getLinePara(transpose_corners[3].x, transpose_corners[3].y, transpose_corners[0].x, transpose_corners[0].y, lp3);
  800. k23 = sqrt(lp3.k * lp3.k + 1);
  801. double processWidth = right_x - left_x; // 重叠区域的宽度
  802. double processHeight = bottom_y - top_y; // 重叠区域的宽度
  803. double alpha = 1; // last_img中像素的权重
  804. for (int i = top_y; i < bottom_y; i++)
  805. {
  806. for (int j = left_x; j < right_x; j++)
  807. {
  808. if (last_img.at<Vec3b>(i, j)[0] == 0 && last_img.at<Vec3b>(i, j)[1] == 0 && last_img.at<Vec3b>(i, j)[2] == 0)
  809. {
  810. continue;
  811. }
  812. // 如果拼接图的该区域内遇到黑点,则完全拷贝上一张拼接图上的点
  813. else if (stitched_image.at<Vec3b>(i, j)[0] == 0 && stitched_image.at<Vec3b>(i, j)[1] == 0 && stitched_image.at<Vec3b>(i, j)[2] == 0)
  814. {
  815. stitched_image.at<Vec3b>(i, j) = last_img.at<Vec3b>(i, j);
  816. }
  817. else if (point_2_line(lp0.k, lp0.b, k20, j, i) < thresh) // 如果点在线的附近
  818. {
  819. stitched_image.at<Vec3b>(i, j) = last_img.at<Vec3b>(i, j);
  820. }
  821. else if (point_2_line(lp1.k, lp1.b, k21, j, i) < thresh) // 如果点在线的附近
  822. {
  823. stitched_image.at<Vec3b>(i, j) = last_img.at<Vec3b>(i, j);
  824. }
  825. else if (point_2_line(lp2.k, lp2.b, k22, j, i) < thresh) // 如果点在线的附近
  826. {
  827. stitched_image.at<Vec3b>(i, j) = last_img.at<Vec3b>(i, j);
  828. }
  829. else if (point_2_line(lp3.k, lp3.b, k23, j, i) < thresh) // 如果点在线的附近
  830. {
  831. stitched_image.at<Vec3b>(i, j) = last_img.at<Vec3b>(i, j);
  832. }
  833. }
  834. }
  835. }
  836. // 把边缘处的点给补全,免得有太多的接缝黑边
  837. void fill_contours(vector<vector<Point>> target_contours, Mat &source_image, Mat &target_image)
  838. {
  839. int h = source_image.rows, w = source_image.cols;
  840. // 对source_image求轮廓,并生成mask
  841. Mat source_gray, target_gray;
  842. cvtColor(source_image, source_gray, COLOR_BGR2GRAY);
  843. cvtColor(target_image, target_gray, COLOR_BGR2GRAY);
  844. Mat tmp_binary;
  845. threshold(source_gray, tmp_binary, 1, 255, THRESH_BINARY);
  846. vector<vector<Point>> source_contours;
  847. vector<Vec4i> hierarchy;
  848. findContours(tmp_binary, source_contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
  849. tmp_binary.release();
  850. // 只留下最大的那个contours
  851. int _max_count = 0;
  852. int _max_idx = 0;
  853. for (int _i = 0; _i < source_contours.size(); _i++)
  854. {
  855. int point_num = source_contours[_i].size();
  856. if (point_num > _max_count)
  857. {
  858. _max_count = point_num;
  859. _max_idx = _i;
  860. }
  861. }
  862. source_contours = vector<vector<Point>>{source_contours[_max_idx]};
  863. Mat mask = Mat(h, w, CV_8UC1, Scalar(0));
  864. fillPoly(mask, source_contours, Scalar(1));
  865. vector<Point> contour = target_contours[0];
  866. int range = 30;
  867. float weight;
  868. int total_num = contour.size();
  869. int line_direction = 0; // 判断当前点所在的直线的方向,0水平或者1垂直
  870. int direction = 0; // 当前点和下一个点连成的线的方向,1从左向右,2从右向左,3从上到下,4从下到上
  871. for (int j = 0; j < total_num; j++)
  872. {
  873. int x = contour[j].x;
  874. int y = contour[j].y;
  875. if (x == 0 || y == 0 || x == w - 1 || y == h - 1 || mask.at<uchar>(y, x) == 0)
  876. continue;
  877. target_image.at<Vec3b>(y, x) = source_image.at<Vec3b>(y, x); // 填充边缘
  878. int d1 = 0, d2 = 0, d3 = 0, d4 = 0; // 当前点在4个方向上的差异值的总和
  879. // 先判断是水平还是垂直方向
  880. int dx = 0, dy = 0;
  881. for (int i = 0; i < 3; i++)
  882. {
  883. if (j - i >= 0)
  884. {
  885. dx += abs(x - contour[j - i].x);
  886. dy += abs(y - contour[j - i].y);
  887. }
  888. if (j + i < total_num)
  889. {
  890. dx += abs(x - contour[j + i].x);
  891. dy += abs(y - contour[j + i].y);
  892. }
  893. }
  894. if (dx < dy)
  895. line_direction = 0; // 水平
  896. if (dx > dy)
  897. line_direction = 1; // 垂直
  898. for (int i = 1; i < 3; i++)
  899. { // 各个方向找三个点,看差值是多少,来判断需要融合的方向
  900. if (line_direction == 0)
  901. {
  902. // 从左向右
  903. if (x + i < h)
  904. d1 += abs(target_gray.at<uchar>(y, x + i) - source_gray.at<uchar>(y, x + i));
  905. // 从右向左
  906. if (x - i >= 0)
  907. d2 += abs(target_gray.at<uchar>(y, x - i) - source_gray.at<uchar>(y, x - i));
  908. }
  909. else
  910. {
  911. // 从上到下
  912. if (y + i < h)
  913. d3 += abs(target_gray.at<uchar>(y + i, x) - source_gray.at<uchar>(y + i, x));
  914. // 从下到上
  915. if (y - i >= 0)
  916. d4 += abs(target_gray.at<uchar>(y - i, x) - source_gray.at<uchar>(y - i, x));
  917. }
  918. }
  919. if (d1 > d2 && d1 > d3 && d1 > d4)
  920. direction = 1;
  921. else if (d2 > d1 && d2 > d3 && d2 > d4)
  922. direction = 2;
  923. else if (d3 > d1 && d3 > d2 && d3 > d4)
  924. direction = 3;
  925. else if (d4 > d1 && d4 > d2 && d4 > d3)
  926. direction = 4;
  927. for (int i = 1; i < range; i++)
  928. {
  929. weight = 1.0 * i / range;
  930. if (direction == 1)
  931. { // 从左到右
  932. if (x + i < w && source_gray.at<uchar>(y, x + i) > 1)
  933. {
  934. target_image.at<Vec3b>(y, x + i)[0] = source_image.at<Vec3b>(y, x + i)[0] * (1 - weight) + target_image.at<Vec3b>(y, x + i)[0] * weight;
  935. target_image.at<Vec3b>(y, x + i)[1] = source_image.at<Vec3b>(y, x + i)[1] * (1 - weight) + target_image.at<Vec3b>(y, x + i)[1] * weight;
  936. target_image.at<Vec3b>(y, x + i)[2] = source_image.at<Vec3b>(y, x + i)[2] * (1 - weight) + target_image.at<Vec3b>(y, x + i)[2] * weight;
  937. }
  938. }
  939. else if (direction == 2)
  940. { // 从右到左
  941. if (x - i >= 0 && source_gray.at<uchar>(y, x - i) > 1)
  942. {
  943. target_image.at<Vec3b>(y, x - i)[0] = source_image.at<Vec3b>(y, x - i)[0] * (1 - weight) + target_image.at<Vec3b>(y, x - i)[0] * weight;
  944. target_image.at<Vec3b>(y, x - i)[1] = source_image.at<Vec3b>(y, x - i)[1] * (1 - weight) + target_image.at<Vec3b>(y, x - i)[1] * weight;
  945. target_image.at<Vec3b>(y, x - i)[2] = source_image.at<Vec3b>(y, x - i)[2] * (1 - weight) + target_image.at<Vec3b>(y, x - i)[2] * weight;
  946. }
  947. }
  948. else if (direction == 3)
  949. { // 从上到下
  950. if (y + i < h && source_gray.at<uchar>(y + i, x) > 1)
  951. {
  952. target_image.at<Vec3b>(y + i, x)[0] = source_image.at<Vec3b>(y + i, x)[0] * (1 - weight) + target_image.at<Vec3b>(y + i, x)[0] * weight;
  953. target_image.at<Vec3b>(y + i, x)[1] = source_image.at<Vec3b>(y + i, x)[1] * (1 - weight) + target_image.at<Vec3b>(y + i, x)[1] * weight;
  954. target_image.at<Vec3b>(y + i, x)[2] = source_image.at<Vec3b>(y + i, x)[2] * (1 - weight) + target_image.at<Vec3b>(y + i, x)[2] * weight;
  955. }
  956. }
  957. else if (direction == 4)
  958. { // 从下到上
  959. if (y - i >= 0 && source_gray.at<uchar>(y - i, x) > 1)
  960. {
  961. target_image.at<Vec3b>(y - i, x)[0] = source_image.at<Vec3b>(y - i, x)[0] * (1 - weight) + target_image.at<Vec3b>(y - i, x)[0] * weight;
  962. target_image.at<Vec3b>(y - i, x)[1] = source_image.at<Vec3b>(y - i, x)[1] * (1 - weight) + target_image.at<Vec3b>(y - i, x)[1] * weight;
  963. target_image.at<Vec3b>(y - i, x)[2] = source_image.at<Vec3b>(y - i, x)[2] * (1 - weight) + target_image.at<Vec3b>(y - i, x)[2] * weight;
  964. }
  965. }
  966. }
  967. }
  968. }
  969. inline float point_2_line(float k, float b, float k2, float x, float y)
  970. {
  971. float distance = abs(k * x + b - y) / k2;
  972. return distance;
  973. }
  974. // 获取直线参数
  975. inline void getLinePara(float x1, float y1, float x2, float y2, LinePara &LP)
  976. {
  977. double m = 0;
  978. // 计算分子
  979. m = x2 - x1;
  980. if (0 == m)
  981. {
  982. LP.k = 10000.0;
  983. LP.b = y1 - LP.k * x1;
  984. }
  985. else
  986. {
  987. LP.k = (y2 - y1) / (x2 - x1);
  988. LP.b = y1 - LP.k * x1;
  989. }
  990. }
  991. // 1从上到下,2从下到上,3从左到右,4从右到左
  992. int get_direction(vector<Point2f> &frame_corners, vector<Point2f> &transpose_corners)
  993. {
  994. float dx = ((transpose_corners[0].x - frame_corners[0].x) +
  995. (transpose_corners[1].x - frame_corners[1].x) +
  996. (transpose_corners[2].x - frame_corners[2].x) +
  997. (transpose_corners[3].x - frame_corners[3].x)) /
  998. 4;
  999. float dy = ((transpose_corners[0].y - frame_corners[0].y) +
  1000. (transpose_corners[1].y - frame_corners[1].y) +
  1001. (transpose_corners[2].y - frame_corners[2].y) +
  1002. (transpose_corners[3].y - frame_corners[3].y)) /
  1003. 4;
  1004. int direction;
  1005. if (abs(dx) > abs(dy))
  1006. {
  1007. if (dx > 0)
  1008. direction = 3;
  1009. else
  1010. direction = 4;
  1011. }
  1012. else
  1013. {
  1014. if (dy > 0)
  1015. direction = 1;
  1016. else
  1017. direction = 2;
  1018. }
  1019. return direction;
  1020. }
  1021. inline int dcmp(float x)
  1022. { // 精度误差比较
  1023. if (x > 1e-14)
  1024. return 1;
  1025. return x < -1e-14 ? -1 : 0;
  1026. }
  1027. float cross(Point2f a, Point2f b, Point2f c) { return (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y); } // 叉积
  1028. inline float CPIA(Point2f a[], Point2f b[], int na, int nb)
  1029. { // 传入两个三角形,求相交部分的凸包
  1030. vector<Point2f> p(20), tmp(20); // 复制点集与临时点集(P其实可以用B来做
  1031. int tn, sflag, eflag; // 每轮相交凸包的点,叉乘符号
  1032. a[na] = a[0], b[nb] = b[0]; // 末点用初点复制方便首末点连边
  1033. for (int k = 0; k <= nb; k++)
  1034. {
  1035. p[k] = b[k];
  1036. }
  1037. for (int i = 0; i < na && nb > 2; i++)
  1038. { // 扫一次A
  1039. sflag = dcmp(cross(a[i + 1], p[0], a[i])); // 取A两点与B第一点求叉乘符号
  1040. for (int j = tn = 0; j < nb; j++, sflag = eflag)
  1041. { // 扫一次B,更新TMP,TN是点数
  1042. if (sflag >= 0)
  1043. tmp[tn++] = p[j]; // 叉乘为正就是B数组的那个点压入
  1044. eflag = dcmp(cross(a[i + 1], p[j + 1], a[i])); // 求叉乘符号
  1045. if ((sflag ^ eflag) == -2)
  1046. tmp[tn++] = get_intersection_point(a[i], a[i + 1], p[j], p[j + 1]); // 求交点
  1047. }
  1048. for (int k = 0; k < tn; k++)
  1049. {
  1050. p[k] = tmp[k];
  1051. }
  1052. nb = tn, p[nb] = p[0]; // TN即TMP点数记到NB
  1053. } // 其实该是NP表示P数组个数,这里省了个变量就用NB表示,下面第二行做参数而已
  1054. if (nb < 3)
  1055. return 0.f; // 相交部分凸包不够三个点,面积就是0
  1056. return PolygonArea(p, nb); // 求出相交凸包部分的面积
  1057. }
  1058. inline float SPIA(vector<Point2f> a, vector<Point2f> b, int na, int nb)
  1059. { // 传入两个多边形的点
  1060. int i, j; // 循环变量
  1061. Point2f t1[4], t2[4]; // 其实T13与T23没用上
  1062. double num1, num2; // 叉乘符号
  1063. float res = 0.f; // 答案初始化
  1064. a[na] = t1[0] = a[0], b[nb] = t2[0] = b[0]; // 初始化T1,T2和ANA,BNB
  1065. for (i = 2; i < na; i++)
  1066. { // 扫一次第一个多边形全部点
  1067. t1[1] = a[i - 1], t1[2] = a[i]; // 每次在第一个多边形取两个点赋给T11,T12
  1068. num1 = dcmp(cross(t1[1], t1[2], t1[0])); // 求出叉乘符号
  1069. if (num1 < 0)
  1070. {
  1071. t1[1] = a[i], t1[2] = a[i - 1];
  1072. }
  1073. for (j = 2; j < nb; j++)
  1074. { // 扫一次第二个多边形全部点
  1075. t2[1] = b[j - 1], t2[2] = b[j]; // 然后再在第二个多边形取两个点赋给T21,T22
  1076. num2 = dcmp(cross(t2[1], t2[2], t2[0])); // 求出叉乘符号
  1077. if (num2 < 0)
  1078. {
  1079. t2[1] = b[j], t2[2] = b[j - 1];
  1080. }
  1081. res += CPIA(t1, t2, 3, 3); // 累加相交部分面积
  1082. }
  1083. }
  1084. return res;
  1085. }
  1086. Point2f get_intersection_point(Point2f a, Point2f b, Point2f c, Point2f d)
  1087. { // 传入四点即两直线,输出交点
  1088. Point2f p = a;
  1089. float t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x));
  1090. p.x += (b.x - a.x) * t;
  1091. p.y += (b.y - a.y) * t;
  1092. return p; // 输出交点,证明用数学方法易证
  1093. }
  1094. inline float PolygonArea(vector<Point2f> p, int n)
  1095. { // 计算多边形面积,三角剖分
  1096. if (n < 3)
  1097. return 0.0;
  1098. if (n >= 24)
  1099. return 0.0;
  1100. float s = p[0].y * (p[n - 1].x - p[1].x);
  1101. p[n] = p[0];
  1102. for (int i = 1; i < n; ++i)
  1103. s += p[i].y * (p[i - 1].x - p[i + 1].x);
  1104. return fabs(s * 0.5); // 叉乘出来是平行四边形面积故/2,且顺逆方向不定,故取ABS变正
  1105. }
  1106. inline float single_quadrangle_iou(vector<Point2f> pts1, vector<Point2f> pts2)
  1107. {
  1108. const float area1 = PolygonArea(pts1, 4);
  1109. const float area2 = PolygonArea(pts2, 4);
  1110. if (area1 < 1e-14 || area2 < 1e-14)
  1111. {
  1112. return 0.f;
  1113. }
  1114. const float intersection = SPIA(pts1, pts2, 4, 4);
  1115. const float iou = intersection / (area1 + area2 - intersection);
  1116. return iou;
  1117. }
  1118. inline float single_box_iou(vector<Point2f> pts1, vector<Point2f> pts2)
  1119. {
  1120. int xmin1 = (int)min_axis(vector<float>{pts1[0].x, pts1[1].x, pts1[2].x, pts1[3].x});
  1121. int xmax1 = (int)max_axis(vector<float>{pts1[0].x, pts1[1].x, pts1[2].x, pts1[3].x});
  1122. int ymax1 = (int)max_axis(vector<float>{pts1[0].y, pts1[1].y, pts1[2].y, pts1[3].y});
  1123. int ymin1 = (int)min_axis(vector<float>{pts1[0].y, pts1[1].y, pts1[2].y, pts1[3].y});
  1124. float area1 = (float)(xmax1 - xmin1) * (ymax1 - ymin1);
  1125. int xmin2 = (int)min_axis(vector<float>{pts2[0].x, pts2[1].x, pts2[2].x, pts2[3].x});
  1126. int xmax2 = (int)max_axis(vector<float>{pts2[0].x, pts2[1].x, pts2[2].x, pts2[3].x});
  1127. int ymax2 = (int)max_axis(vector<float>{pts2[0].y, pts2[1].y, pts2[2].y, pts2[3].y});
  1128. int ymin2 = (int)min_axis(vector<float>{pts2[0].y, pts2[1].y, pts2[2].y, pts2[3].y});
  1129. float area2 = (float)(xmax2 - xmin2) * (ymax2 - ymin2);
  1130. int inter_xmin = MAX(xmin1, xmin2);
  1131. int inter_xmax = MIN(xmax1, xmax2);
  1132. int inter_ymin = MAX(ymin1, ymin2);
  1133. int inter_ymax = MIN(ymax1, ymax2);
  1134. float inter_area = (float)(inter_xmax - inter_xmin) * (inter_ymax - inter_ymin);
  1135. float union_area = (area1 + area2 - inter_area);
  1136. if (union_area < 1e-14)
  1137. {
  1138. return 0.f;
  1139. }
  1140. float iou = 1.0 * inter_area / union_area;
  1141. return iou;
  1142. }
  1143. // 柱面投影
  1144. void cylindrical_projection(Mat &img, Mat &output, float angle)
  1145. {
  1146. float w = img.cols;
  1147. float h = img.rows;
  1148. Mat map_img = Mat(h, w, CV_8UC3, Scalar(0));
  1149. float f = (w / (90 - angle) * 5) / atan(M_PI / 15);
  1150. float cx = w / 2.0f;
  1151. float cy = h / 2.0f;
  1152. int max_col = 0;
  1153. for (int i = 0; i < img.rows; i++)
  1154. {
  1155. for (int j = 0; j < img.cols; j++)
  1156. {
  1157. float x = j;
  1158. float y = i;
  1159. float x1 = f * atan((x - cx) / f) + f * atan(cx / f);
  1160. float y1 = f * (y - cy) / sqrt((x - cx) * (x - cx) + f * f) + cy;
  1161. int col = (int)(x1 + 0.5f); // 加0.5是为了四舍五入
  1162. int row = (int)(y1 + 0.5f); // 加0.5是为了四舍五入
  1163. max_col = col > max_col ? col : max_col;
  1164. if (col < img.cols && row < img.rows)
  1165. {
  1166. map_img.at<Vec3b>(row, col)[0] = img.at<Vec3b>(i, j)[0];
  1167. map_img.at<Vec3b>(row, col)[1] = img.at<Vec3b>(i, j)[1];
  1168. map_img.at<Vec3b>(row, col)[2] = img.at<Vec3b>(i, j)[2];
  1169. }
  1170. }
  1171. }
  1172. output = map_img(Rect(0, 0, max_col, h));
  1173. }