在 OpenCV 中选择图像的非矩形 ROI 的最有效方法是什么?

Mr *_*agi 7 python opencv numpy

我想创建一个二进制图像掩码,在 python 中只包含 1 和 0。感兴趣区域(白色)是非矩形的,由 4 个角点定义,例如如下所示: 在此处输入图片说明

在我的方法中,我首先计算上下 ROI 边界的线方程,然后检查每个掩码元素,如果它比边界小或大。代码正在运行,但速度太慢了。一个 2000x1000 的面具需要 4 秒的时间来处理我的机器。

from matplotlib import pyplot as plt 
import cv2
import numpy as np
import time

def line_eq(line):
    """input:
            2 points of a line
       returns: 
            slope and intersection of the line
    """
    (x1, y1), (x2, y2) = line
    slope = (y2 - y1) / float((x2 - x1))
    intersect = int(slope * (-x1) + y1)

    return slope,intersect

def maskByROI(mask,ROI):
    """
        input: 
            ROI: with 4 corner points e.g. ((x0,y0),(x1,y1),(x2,y2),(x3,y3))
            mask: 
        output: 
            mask with roi set to 1, rest to 0

    """


    line1 = line_eq((ROI[0],ROI[1]))
    line2 = line_eq((ROI[2],ROI[3]))

    slope1 = line1[0] 
    intersect1 = line1[1]

    #upper line
    if slope1>0:
        for (x,y), value in np.ndenumerate(mask):
                if y > slope1*x +intersect1:
                    mask[x,y] = 0
    else:   
        for (x,y), value in np.ndenumerate(mask):
                if y < slope1*x +intersect1:
                    mask[x,y] = 0
    #lower line
    slope2 = line2[0]
    intersect2 = line2[1]
    if slope2<0:
        for (x,y), value in np.ndenumerate(mask):
                if y > slope2*x +intersect2:
                    mask[x,y] = 0
    else:   
        for (x,y), value in np.ndenumerate(mask):
                if y < slope2*x +intersect2:
                    mask[x,y] = 0

    return mask



mask = np.ones((2000,1000))

myROI = ((750,0),(900,1000),(1000,1000),(1500,0))

t1 = time.time()
mask = maskByROI(mask,myROI)
t2 = time.time()

print "execution time: ", t2-t1


plt.imshow(mask,cmap='Greys_r')
plt.show()
Run Code Online (Sandbox Code Playgroud)

有什么更有效的方法来创建这样的面具?

numpy、OpenCV 或类似库提供的非矩形形状是否有类似的解决方案?

szy*_*zym 6

使用以下命令绘制蒙版fillPoly

mask = np.ones((1000, 2000))                              # (height, width)
myROI = [(750, 0), (900, 1000), (1000, 1000), (1500, 0)]  # (x, y)
cv2.fillPoly(mask, [np.array(myROI)], 0)
Run Code Online (Sandbox Code Playgroud)

这应该需要大约 1 毫秒。