繁体   English   中英

如何在仅由 cv2.minAreaRect 创建的框内进行图像处理?

[英]How to do image processing inside box created by cv2.minAreaRect only?

我在原始图像中绘制了一个旋转的矩形。 是否可以只在旋转后的矩形框中进行图像处理而不从原始图像中裁剪掉它? 在此处输入图像描述 在此处输入图像描述

original = cv2.imread(r'image.jpg')

ori_img = original.copy()
img = cv2.cvtColor(ori_img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img,(5,5),0)
_, thresh = cv2.threshold(img, 130, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for cnt in contours:
    [x, y, w, h] = cv2.boundingRect(cnt)
    if (w*h) >= 10000:
        box = cv2.minAreaRect(np.asarray(cnt))
        pts = cv2.boxPoints(box)
        pts = np.int0(pts)
cv2.drawContours(ori_img, [pts], 0, (0,255,0), 3)    
cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)
cv2.imshow('Frame',ori_img)
k = cv2.waitKey(0)

简短的回答:没有

没有 OpenCV 函数采用RotatedRect来限制它们正在处理的区域。

长答案:也许

某些 OpenCV 函数可以采用掩码参数。 许多人没有。

要从旋转的矩形计算掩码,请使用boxPoints ,然后将颜色为255的填充多边形绘制到 dtype uint8和形状(height, width)的数组中

mask = np.zeros((height, width), dtype=np.uint8)

# pts from boxPoints is a float32 array, fillPoly only likes integers
cv.fillPoly(
    img=mask,
    pts=np.round(pts).astype(np.int32).reshape((-1, 1, 2)), # round, cast, reshape into 2-channel column vector
    color=255)

更长的答案:做你的操作,然后使用掩码复制回来。

source = ...
altered = your_operations(source)
source[mask != 0] = altered[mask != 0]

为了减少工作量,您也可以在子区域上进行操作(然后使用掩码复制回来)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM