使用OpenCV查找图像中矩形的位置

 

import cv2

image = cv2.imread('1.jpg')
blur = cv2.pyrMeanShiftFiltering(image, 11, 21)
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.015 * peri, True)
    if len(approx) == 4:
        x,y,w,h = cv2.boundingRect(approx)
        #x,y,w,h = cv2.minAreaRect(approx)
        print(approx)
        cv2.rectangle(image,(x,y),(x+w,y+h),(36,255,12),2)

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()

 

 

 

For MORE

 

 

 

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用OpenCV的C++例程,用于在图像检测矩形区域并进行blob分析: ```c++ #include <opencv2/opencv.hpp> #include <iostream> #include <vector> using namespace cv; using namespace std; int main() { // 读取图像文件 Mat img = imread("test.jpg", IMREAD_GRAYSCALE); // 二值化图像 Mat binary_img; threshold(img, binary_img, 0, 255, THRESH_BINARY_INV | THRESH_OTSU); // 查找轮廓 vector<vector<Point>> contours; findContours(binary_img, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // 筛选矩形轮廓 vector<Rect> rects; for (size_t i = 0; i < contours.size(); i++) { Rect rect = boundingRect(contours[i]); if (rect.width > 10 && rect.height > 10 && rect.width < img.cols && rect.height < img.rows) { rects.push_back(rect); } } // 显示矩形 for (size_t i = 0; i < rects.size(); i++) { rectangle(img, rects[i], Scalar(255, 0, 0), 2); } // 显示图像 imshow("result", img); waitKey(); // 对每个矩形进行blob分析 for (size_t i = 0; i < rects.size(); i++) { // 提取矩形区域 Mat roi = binary_img(rects[i]); // 构建blob分析器 SimpleBlobDetector::Params params; params.minDistBetweenBlobs = 10; // blob之间的最小距离 params.filterByArea = true; // 根据面积筛选blob params.minArea = 50; // blob的最小面积 params.maxArea = 10000; // blob的最大面积 params.filterByCircularity = true; // 根据圆形度筛选blob params.minCircularity = 0.8; // blob的最小圆形度 params.maxCircularity = 1.0; // blob的最大圆形度 SimpleBlobDetector blob_detector(params); // 检测blob vector<KeyPoint> keypoints; blob_detector.detect(roi, keypoints); // 显示结果 Mat result; drawKeypoints(roi, keypoints, result, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS); imshow("result", result); waitKey(); } return 0; } ``` 此示例使用OpenCV的`findContours`函数查找图像的轮廓,然后使用矩形边界框筛选出矩形轮廓。然后,它使用`SimpleBlobDetector`类对每个矩形进行blob分析,并在每个矩形上绘制检测到的blob。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值