【问题标题】:Mask out ROI without changing the image size在不改变图像大小的情况下屏蔽 ROI
【发布时间】:2019-10-22 11:18:50
【问题描述】:

我得到了一些养牛场的图像。每个图像假设只覆盖两个笔(小牛房)。但是,相机也会覆盖相邻的笔。我需要摆脱相邻笔的区域。

输入图像 -

输出图像 -

我尝试了以下命令,它完成了这项工作。但是,它缩小了图像的大小,使输出为第 2 行中生成的边界框大小。输出变得比原始图像小。在这种情况下,原始图像为 2560x1440,但输出为 2536x1406。

import cv2
import numpy as np
import matplotlib.pyplot as plt

frame = cv2.imread("input.jpg")
# pts - location of the 4 corners of the roi
pts = np.array([[6, 1425],[953, 20 ],[1934, 40 ], [2541,1340]])
rect = cv2.boundingRect(pts)
x, y, w, h = rect
croped = frame[y:y + h, x:x + w].copy()
pts = pts - pts.min(axis=0)
mask = np.zeros(croped.shape[:2], np.uint8)
cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)
frame_roi = cv2.bitwise_and(croped, croped, mask=mask)
cv2.imwrite("output.jpg", frame_roi)

但是,我需要输出图像的大小与输入图像的大小相同,并且 ROI 之外的任何内容都必须是黑/白(如下所示,虽然它是不同的图片)。白色或黑色蒙版区域都可以工作(上面的输出是黑色的,下面的手工编辑的图像是白色的)。有没有办法用 opencv 或任何其他库来做到这一点?

【问题讨论】:

  • 您能提供原始尺寸的图片吗?这里被下采样到 640x360,你的代码显然不能在上面运行。
  • @Paul92 我稍微编辑了代码并在图像上进行了测试,然后将结果上传到这里。请立即检查。

标签: python image opencv image-processing computer-vision


【解决方案1】:

错误在这一行

mask = np.zeros(croped.shape[:2], np.uint8)

它应该与您的原始/输入图像的大小完全相同。因此,将其更改为原始形状应该会给出正确的输出图像。

mask = np.zeros(original_image.shape, np.uint8)

这是输出图像的形状

(1440L、2560L、3L)

import cv2
import numpy as np

original_frame = cv2.imread("1.jpg")
frame = original_frame.copy()

# pts - location of the 4 corners of the roi
pts = np.array([[6, 1425],[953, 20],[1934, 40], [2541,1340]])
(x,y,w,h) = cv2.boundingRect(pts)

pts = pts - pts.min(axis=0)
mask = np.zeros(original_frame.shape, np.uint8)
cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)
result = cv2.bitwise_and(original_frame, mask)

cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.imwrite('result.png', result)
print(result.shape)
cv2.waitKey(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多