【问题标题】:How to do image processing inside box created by cv2.minAreaRect only?如何在仅由 cv2.minAreaRect 创建的框中进行图像处理?
【发布时间】:2021-11-27 08:58:13
【问题描述】:

我在原始图像中绘制了一个旋转的矩形。是否可以仅在旋转的矩形框中进行图像处理而不将其从原始图像中裁剪出来?

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)

【问题讨论】:

  • 你想做什么图像处理?
  • @Abhi25t 模糊、阈值、canny 等
  • 你说的是什么意思:没有从原始图像中裁剪出来你的绘图也不是矩形

标签: python numpy opencv image-processing opencv-python


【解决方案1】:

简短回答:

没有任何 OpenCV 函数需要 RotatedRect 来限制它们正在处理的区域。

长答案:也许

一些 OpenCV 函数可以采用 mask 参数。许多人没有。

要从旋转的矩形计算掩码,请使用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]

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

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2018-01-12
    • 2020-04-26
    • 2013-02-03
    • 2021-09-25
    • 2021-04-23
    相关资源
    最近更新 更多