我正在尝试一次将阈值应用于图像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()
答案 0 :(得分:3)
有几种方法可以做到,所以我将从最简单,最快,更灵活,更慢...
最简单最快的方法是,如果您的遮罩区域像您一样非常简单:
import cv2
# 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)
如果您的遮罩区域更复杂,例如使用复合形状(轮廓或圆形),您将对整个图像进行阈值处理,然后创建相同大小的填充黑色的蒙版,以白色绘制形状,然后根据蒙版在每个像素处选择阈值图像或原始图像:< / p>
# 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
mask = cv2.circle(mask,(200,100),100,1,-1)
# Threshold the entire image
ret,thresh = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
# Select either the original or the thresholded image at each pixel, depending on the mask
img = np.where(mask>0,thresh,img)
这是年轻流氓的原始图像:
关键字:Python,OpenCV,Numpy,图像,图像处理,蒙版,蒙版,阈值,过滤器,ROI,感兴趣区域