首页 > 解决方案 > 如何使用 Python 沿着带有矩形边界框的斑点/轮廓的主轴裁剪图像

问题描述

我想裁剪一个带有手绘橙色突出显示区域的图像,如下所示,

在此处输入图像描述

结果应该是沿着斑点或轮廓的长轴裁剪的图像,带有矩形边界框,如下所示,

在此处输入图像描述

这是我尝试过的,

import numpy as np
import cv2

# load the image
image = cv2.imread("frame50.jpg", 1)

#color boundaries [B, G, R]
lower = [0, 3, 30]
upper = [30, 117, 253]

# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")

# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask=mask)

ret,thresh = cv2.threshold(mask, 50, 255, 0)
if (int(cv2.__version__[0]) > 3):
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
else:
    im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    # find the biggest countour (c) by the area
    c = max(contours, key = cv2.contourArea)
    x,y,w,h = cv2.boundingRect(c)
    ROI = image[y:y+h, x:x+w]
cv2.imshow('ROI',ROI)
cv2.imwrite('ROI.png',ROI)

cv2.waitKey(0)

这似乎在大多数情况下都不起作用。对于某些图像,会发生以下情况,

在此处输入图像描述

我想知道是否有更好的方法来解决这个问题,或者我如何修复我现在拥有的东西。请注意,突出显示的区域是手绘的,可以是任何形状,但它是封闭的,不能保持打开状态,颜色在所有情况下,亮点是橙色本身的阴影。有没有办法只保留圈内的内容而将圈外的所有内容都涂黑?

EDIT1: 我能够通过更多地改变阈值来修复错误的剪辑。但我现在的主要疑问是:有没有办法只保留圈内的内容而将圈外的所有内容都涂黑?我可以看到如下所示的面具,

在此处输入图像描述

如何使用相同的矩形边界框填充此蒙版并保留圆圈内的内容并将其外的所有内容涂黑?

标签: pythonimageopencvblobopencv-contour

解决方案


你有没有尝试过

image[x:x+w, y:y+h]

你能用下面的代码检查 bbox

cv2.rectangle(thresh,(x,y),(x+w,y+h),(255,0,0),2)

推荐阅读