【问题标题】:Is there a way to apply a threshold to an image 1 row at a time有没有办法一次将阈值应用于图像 1 行
【发布时间】:2019-08-30 04:12:56
【问题描述】:

我正在尝试一次将阈值应用于图像 1 行。我希望能够选择阈值开始和结束的行。前任。如果我有一个 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()

【问题讨论】:

  • 只需将图像的所需切片提供给当前阈值方法,然后将其分配回您从中剪切的位置。

标签: python-3.x image matplotlib image-processing image-thresholding


【解决方案1】:

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

最简单最快的,如果你的蒙版区域和你的一样简单:

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、感兴趣区域

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2019-09-04
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多