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

标签 python opencv numpy

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

在我的方法中,我首先计算 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()

创建这样的 mask 的更有效方法是什么?

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

最佳答案

使用 fillPoly 绘制 mask :

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)

这应该需要 ~1 毫秒。

关于python - 在 OpenCV 中选择图像的非矩形 ROI 的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37624509/

相关文章:

python - matplotlib:相同大小的子图?

python - 使用 MultiIndex df (pandas) 进行 bool 索引

python - CUDA(GPU) 作为 OpenCV 后端

c++ - 线程会影响 Raspberry Pi 上的图像处理性能吗?

python - 使用辛普森规则整合正态分布

matlab - 从 Matlab 文件导入时为 "LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd"

Python - 从文本文件中查找行号

python - 从 Pandas Series 中选择行,其中行是数组

sorting - 我想使用轮廓检测​​对从图像中提取的单词按出现的顺序进行排序

python - 当数组 ndim 直到运行时才知道时,如何获取 numpy 子数组 View ?