[英]How to do image processing inside box created by cv2.minAreaRect only?
I draw a rotated rectangle in the original image.我在原始图像中绘制了一个旋转的矩形。 Is it possible to do image processing in the rotated rectangle box only without cropping it out from the original image?是否可以只在旋转后的矩形框中进行图像处理而不从原始图像中裁剪掉它?
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)
Short answer: no .简短的回答:没有。
No OpenCV functions take a RotatedRect
to limit the area they are working on.没有 OpenCV 函数采用RotatedRect
来限制它们正在处理的区域。
Long answer: maybe .长答案:也许。
Some OpenCV functions can take a mask argument.某些 OpenCV 函数可以采用掩码参数。 Many don't.许多人没有。
To calculate a mask from the rotated rectangle, use boxPoints
and then draw a filled polygon with color 255
into an array of dtype uint8
and shape (height, width)
要从旋转的矩形计算掩码,请使用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)
Longer answer: do your operations, then copy back using the mask.更长的答案:做你的操作,然后使用掩码复制回来。
source = ...
altered = your_operations(source)
source[mask != 0] = altered[mask != 0]
To reduce the amount of work, you can do your operations on a subregion too (and then use mask to copy back).为了减少工作量,您也可以在子区域上进行操作(然后使用掩码复制回来)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.