python - 在 OpenCV 中从 ROI 中裁剪矩形扩展

标签 python opencv image-processing shapes extract

我有这张图片:

This is the image I want to work on

我想从整个 ROI 中提取下面突出显示的矩形扩展。

Rectangluar extensions to extract

最佳答案

这是使用 morphological operations 的简单方法+ 使用cv2.contourArea()

进行轮廓过滤 <小时/>

大津阈值->形态闭运算+反转->结果

代码

import cv2

# Load image, convert to grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Create kernel and morph close 
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=5)

# Find contours and filter using contour area
cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100 and area < 25000:
        cv2.drawContours(image, [c], -1, (36,255,12), 4)

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

关于python - 在 OpenCV 中从 ROI 中裁剪矩形扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59509049/

相关文章:

Python 如何使用 HoughLines 和 OpenCV 检测图像中的垂直线和水平线?

c++ - 为什么霍夫变换检测到两条线而只有一条线

python - 检测目标图像上的弹孔

python - 如何从图像转换中计算张量乘数?

python - 为什么在按两个条件对数据框进行子集化后,无法将值应用于整个 pandas 列?

python - 无法获得 tiff 图像分辨率

python - 在 Python 中使用 OpenCV 旋转图像时指定背景颜色

python - 如何从 realsense L515 记录深度流

image-processing - 如何通过脚本将多个 ROI 裁剪为 DM 中的图像?

python - 导入 win32com.client 错误