掩盖ROI而无需更改图像大小

时间:2019-06-06 22:54:32

标签: python python-3.x opencv image-processing computer-vision

我有一些养牛场的照片。每个图像假定只覆盖两支笔(小牛房)。但是,相机也可以遮盖相邻的笔。我需要摆脱相邻笔的区域。

输入图像-

enter image here

输出图像-

enter image here

我尝试了以下命令,它可以完成工作。但是,它会缩小图像的大小,并输出第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或任何其他库来做到这一点?

enter image description here

1 个答案:

答案 0 :(得分:2)

enter image description here

错误在这一行

poly a b x = sum . map (\(ai, bi) -> ai * (x ** bi)) . zip (fromIntegral <$> a) $ fromIntegral <$> b

,其大小应与原始/输入图像完全相同。因此,将其更改为原始形状应该可以提供正确的输出图像。

set.seed(123)
Mydata = sample(x=100:300, size = 500, replace = T)
Mydata = c(Mydata, 1, 500)
boxplot(Mydata)

这是输出图像的形状

  

(1440L,2560L,3L)

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