分享

RotatedRect 校正带旋转角度的矩形

 魏正钦的图书馆 2018-11-28
  1. #include "opencv2/highgui/highgui.hpp"
  2. #include <cv.h>
  3. using namespace cv;
  4. void main()
  5. {
  6. Mat img = imread("C:/rect1.png");
  7. Mat img_gray;
  8. cvtColor(img, img_gray, CV_BGR2GRAY);
  9. Mat thresh_img(img.size(), CV_8UC1);
  10. threshold(img_gray, thresh_img, 230, 255, THRESH_BINARY_INV);
  11. imshow("thresh", thresh_img);
  12. waitKey();
  13. vector<vector<Point>> contours;
  14. findContours(thresh_img, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  15. RotatedRect mr = minAreaRect(Mat(contours[0]));
  16. Mat DrawImg(img.size(), img.type(), Scalar(255, 255, 255));
  17. Point2f vectpoint[4];
  18. mr.points(vectpoint);
  19. for (int i = 0; i<4; i++)
  20. {
  21. line(DrawImg, vectpoint[i], vectpoint[(i + 1) % 4], Scalar(255, 0, 0), 2);
  22. }
  23. imshow("drawimg", DrawImg);
  24. waitKey();
  25. float angle = 0.0;
  26. Size si = mr.size;
  27. if (mr.size.width <= mr.size.height)
  28. {
  29. angle = mr.angle + 90;
  30. int tm = si.width;
  31. si.width = si.height;
  32. si.height = tm;
  33. //swap(si.width, si.height);
  34. }
  35. else
  36. {
  37. angle = mr.angle;
  38. }
  39. Mat rotmat = getRotationMatrix2D(mr.center, angle, 1);
  40. Mat deal_img;
  41. warpAffine(img, deal_img, rotmat, img.size(), CV_INTER_CUBIC);
  42. imshow("deal_img", deal_img);
  43. waitKey();
  44. Mat rRect;
  45. getRectSubPix(deal_img, si, mr.center, rRect);
  46. imshow("截取的矩形区域", rRect);
  47. waitKey();
  48. }

 

        

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约