有没有办法一次将阈值应用于图像 1 行

Is there a way to apply a threshold to an image 1 row at a time

我正在尝试一次将阈值应用于图像 1 行。我希望能够 select 阈值开始和结束的行。前任。如果我有一张 1000 x 1000 的图像,我想应用从第 200 行开始到第 850 行结束的阈值。目前我可以将阈值应用于整个图像。

img = cv2.imread("*.png",0)
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)

titles = ['Original Image','BINARY']
images = [img, thresh1]

for i in range(2):
    plt.subplot(1,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

有几种方法可以做到这一点,所以我将从最简单和最快的方法,到更灵活和更慢的方法...

最简单和最快的,如果你的遮罩区域像你的一样非常简单:

import cv2
import numpy as np

# Load Paddington as greyscale
img = cv2.imread('paddington.png',0)

# Define a region of interest, in this case entire rows 100-300
ROI = slice(100,300) 

# Threshold the region of interest, and reinsert back into image
ret,img[ROI] = cv2.threshold(img[ROI],127,255,cv2.THRESH_BINARY)  

请注意,我只在一个地方将 ROI 声明为一个变量,这样,如果您更改遮罩的大小,等号两边都保持正确 - 避免维护问题!


如果您的蒙版区域不是整行,您可以创建一个切片元组:

# Declare ROI
ROI = slice(100,300),slice(10,390)

# Threshold with mask
ret,img[ROI] = cv2.threshold(img[ROI],127,255,cv2.THRESH_BINARY)


如果你的遮罩区域比较复杂,例如复合形状、轮廓或圆形,您仍然可以仅对感兴趣的蒙版区域设置阈值!首先创建一个相同大小的黑色填充蒙版,然后用白色绘制形状,然后将阈值应用于感兴趣的蒙版区域:

# Make a mask the same size as the image and fill with black
mask = np.zeros_like(img)

# Draw a filled white circle onto the black mask to define a region of interest
mask = cv2.circle(mask,(200,100),100,255,-1) # -1 to fill inside circle 
ROI = np.nonzero(mask)

# Threshold the region of interest, and reinsert back into image
ret, mask_thresholded = cv2.threshold(img[ROI],127,255,cv2.THRESH_BINARY) 
img[ROI] = mask_thresholded.reshape(-1)


这里是小流氓原图:

关键字:Python、OpenCV、Numpy、图像、图像处理、遮罩、遮罩、阈值、过滤器、ROI、感兴趣区域