Using Python OpenCV, How would you extract an image area inside a particular color bounding box?
鉴于我手动绘制了一个彩色边框的照片,
我想复制/裁剪图像内容,以将内容保留在边框内。
目标是检测该颜色边界框,然后使用该边界框告诉脚本复制/裁剪的位置。
我已经试验了轮廓,但是看来我需要额外的步骤。
也许是一种方法:
- 检测边界区域
- 找到最小的区域(框线的厚度可以变化,所以我需要内部边界区域-边界最终将是物理世界中的彩色海报板切口框)
- 脚本为该区域创建遮罩
- 抓取图像
可能有更好的方法。
最好的方法是什么?
我将使用哪些Python OpenCV方法?
基于当前的实验代码(我正在探索通过轮廓尺寸获取面积,但我认为我需要更好的轮廓代码):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import numpy as np import cv2 image_dir ="/Users/admin/Documents/dir/dir2/" im = cv2.imread(image_dir+'test_image_bounded.png') imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,176,190,43) #ret,thresh = cv2.threshold(imgray,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) areaArray = [] count = 1 for i, c in enumerate(contours): area = cv2.contourArea(c) areaArray.append(area) #first sort the array by area sorteddata = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True) #find the nth largest contour [n-1][1], in this case 2 largestcontour = sorteddata[0][2] #draw it x, y, w, h = cv2.boundingRect(largestcontour) cv2.drawContours(im, largestcontour, -1, (255, 0, 0), 2) cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 2) cv2.imwrite(image_dir+'output.jpg', im) |
编辑--------------------------------
通过颜色检测,形态学和第二大阈值,我设法获得了不错的结果
这是一些相关的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | green_MIN = np.array([45, 25, 25],np.uint8) green_MAX = np.array([55, 255, 255],np.uint8) hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) frame_threshed = cv2.inRange(hsv_img, green_MIN, green_MAX) #image = cv2.imread('...') # Load your image in here # Your code to threshold #image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 45, 0) # Perform morphology se = np.ones((20,20), dtype='uint8') image_close = cv2.morphologyEx(frame_threshed, cv2.MORPH_CLOSE, se) |
HSV值很痛苦。我想使那部分自动化。
这有助于获得价值:
HSV Pixel Values in OpenCV
我的快速建议是:
1)由于矩形为绿色,因此按颜色过滤。 图像本身中也可能存在绿色,但这会减少误报。
2)检测形成矩形的线。
现在,可以通过多种方式完成此操作。 一种更通用的方法是使用霍夫变换。 我不知道可以直接搜索矩形的实现,尽管您也可以实现。 HoughLinesP函数将找到线,您可以选择形成矩形的线。
但是,在您的应用程序中,您可能有非常严格的假设,这将使此问题更加容易。 如果边界框从未旋转过,则可以简单地遍历行和列,以找到具有所要颜色最大像素的行和列。 可以将其扩展为寻找连续的像素以找到线段,但是甚至没有必要。