任务描述:将小装甲板上的小正方形识别并抠出
    up.png

    1. #include<iostream>
    2. #include<opencv2/opencv.hpp>
    3. #include<highgui/highgui.hpp>
    4. #include<imgproc/imgproc.hpp>
    5. using namespace std;
    6. using namespace cv;
    7. void fun(){
    8. Mat srcImage,dstImage1,dstImage2,dstImage3;
    9. srcImage=imread(/home/ma/下载/photo.jpg);
    10. cvtColor(srcImage,dstImage1,COLOR_BGR2GRAY);
    11. threshold(dstImage1,dstImage2,180,255,THRESH_BINARY);
    12. imshow(2,dstImage2);
    13. dstImage3=Mat::zeros(srcImage.size(),srcImage.type());
    14. vector<vector<Point>>contours;
    15. vector<Vec4i>hierarchy;
    16. vector<Point>point;
    17. findContours(dstImage2,contours,hierarchy,RETR_CCOMP,CHAIN_APPROX_NONE);
    18. for(int i=0;i<contours.size();i++){
    19. approxPolyDP(contours[i], point, 1, true);
    20. Rect rect=boundingRect(contours[i]);
    21. Point pt=Point(rect.width,rect.height);
    22. Point pr=Point(-rect.width,rect.height);
    23. double x=double(MIN(rect.width,rect.height))/double(MAX(rect.width,rect.height));
    24. if((pt.x*pr.x)+(pt.y*pr.y)>0&&(pt.x*pt.x)+(pt.y*pt.y)-(pr.x*pr.x)-(pr.y*pr.y)==0&&point.size()==4&&x>0.9){
    25. drawContours(dstImage3,contours,i,Scalar(0,255,255),2);
    26. }
    27. } imshow(dst,dstImage3);
    28. waitKey(0);
    29. }
    30. int main(){
    31. fun();
    32. return 0;
    33. }