Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在OpenCV中从ROI裁剪矩形扩展_Python_Opencv_Image Processing_Shapes_Extraction - Fatal编程技术网

Python 在OpenCV中从ROI裁剪矩形扩展

Python 在OpenCV中从ROI裁剪矩形扩展,python,opencv,image-processing,shapes,extraction,Python,Opencv,Image Processing,Shapes,Extraction,我有这样的图像: 我想从整个ROI中提取下面突出显示的矩形扩展 这里有一个简单的方法,使用+轮廓过滤和cv2.contourArea() 大津的阈值->形态闭合+反转->结果 代码 导入cv2 #加载图像,转换为灰度,大津阈值 image=cv2.imread('1.png') 灰色=cv2.CVT颜色(图像,cv2.COLOR\u BGR2GRAY) thresh=cv2.阈值(灰色,0,255,cv2.thresh\u二进制\u INV+cv2.thresh\u OTSU)[1] #

我有这样的图像:

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


这里有一个简单的方法,使用+轮廓过滤和
cv2.contourArea()


大津的阈值
->
形态闭合+反转
->
结果

代码

导入cv2
#加载图像,转换为灰度,大津阈值
image=cv2.imread('1.png')
灰色=cv2.CVT颜色(图像,cv2.COLOR\u BGR2GRAY)
thresh=cv2.阈值(灰色,0,255,cv2.thresh\u二进制\u INV+cv2.thresh\u OTSU)[1]
#创建内核和变形关闭
kernel=cv2.getStructuringElement(cv2.morp_RECT,(9,9))
close=255-cv2.morphologyEx(thresh,cv2.MORPH\u close,kernel,迭代次数=5)
#查找轮廓并使用轮廓区域进行过滤
cnts=cv2.findContours(关闭、cv2.RETR_树、cv2.CHAIN_近似、简单)
如果len(cnts)==2个其他cnts[1],则cnts=cnts[0]
对于碳纳米管中的碳:
面积=cv2。轮廓面积(c)
如果面积大于100且面积小于25000:
cv2.等高线图(图[c],-1,(36255,12),4)
cv2.imshow('thresh',thresh)
cv2.imshow(“关闭”,关闭)
cv2.imshow(“图像”,图像)
cv2.waitKey()

将是答案。不,这对我不起作用,因为矩形是整个对象的一部分,不位于边缘,因此边缘检测不会将想要的矩形与对象区分开来。欢迎使用stackoverflow。这不是免费的代码编写服务。它也不是教程或网络搜索的替代品。请阅读。然后回答您的问题并添加您迄今为止尝试过的代码。当你运行它时会发生什么?你以为会发生什么?有错误吗?
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()