【发布时间】:2015-08-15 15:31:16
【问题描述】:
给定一张我手动绘制的彩色边界框的照片, 我想复制/裁剪图像内容,以将内容保留在边界框内。
目标是检测颜色边界框,然后使用它告诉脚本复制/裁剪的位置。
我已经尝试过轮廓,但似乎我需要额外的步骤。
也许是一种方法:
- 检测有界区域
- 找到最小的区域(框线的粗细可能不同,所以我需要内部边界区域 - 边界最终将是物理世界中的彩色海报板剪切框)
- 脚本为该区域创建掩码
- 抓图
可能有更好的方法; 解决此问题的最佳方法是什么? 我会使用哪些 Python OpenCV 方法?
基于我目前的实验代码(我正在探索按轮廓大小获取区域,但我认为我需要更好的轮廓代码):
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)
编辑--------------------------------
我已经通过颜色检测、形态学和抓取第二大阈值获得了一些相当不错的结果
以下是一些相关代码:
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 值很痛苦;我想自动化那部分。 这有助于获得价值: https://achuwilson.wordpress.com/2012/02/14/hsv-pixel-values-in-opencv/
【问题讨论】:
标签: python image opencv computer-vision