我想提取图像上以任意形状标记的一个或多个区域(形状边缘始终具有相同的颜色-红色)。标记的区域都具有大约相同的大小(并非完全相同),我希望切出的矩形具有相同的结果大小。
你能给我一个提示怎么做吗?我猜一个人可以在Python中使用opencv来完成这项任务,但是我对此并不熟悉,因此感谢您的帮助!
编辑:添加了一个示例图像,目标是通过相同大小的矩形提取红色区域。
最佳答案
这是在Python / OpenCV中执行此操作的一种方法。
输入:
import cv2
import numpy as np
# read image
img = cv2.imread('monet_shapes.png')
# threshold on red regions
lowerBound = np.array([0, 0, 150]);
upperBound = np.array([100, 100, 255]);
thresh = cv2.inRange(img, lowerBound, upperBound);
# apply morphology to ensure regions are continuous outlines and no gaps
kernel = np.ones((9,9), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# get external contours
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
wmax = 0
hmax = 0
# get bounding boxes and max width and max height from all boxes and centers
centers = []
for cntr in contours:
# get bounding boxes
x,y,w,h = cv2.boundingRect(cntr)
cx = x + w // 2
cy = y + h // 2
cent = [cx,cy]
centers.append(cent)
if w > wmax:
wmax = w
if h > hmax:
hmax = h
print(wmax,hmax)
# show thresh and result
cv2.imshow("thresh", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save threshold
cv2.imwrite("monet_shapes_thresh.png",thresh)
# crop bounding boxes of size maxw, maxh about centers and save
i = 1
for cent in centers:
cx = cent[0]
cy = cent[1]
box = img[cy-hmax//2:cy+hmax//2, cx-wmax//2:cx+wmax//2]
cv2.imwrite("blackbox_result_{0}.png".format(i),box)
i = i + 1
阈值图片:
结果出现了5个裁剪区域:
关于python - 通过相同大小的周围矩形提取图像中的标记区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60967038/