【问题标题】:binarization an image grayscale二值化图像灰度
【发布时间】:2021-01-27 21:15:34
【问题描述】:

我是 python 新手,我的问题是关于编辑图像灰度的一些变化,我想对此图像进行二值化,大于 100 的像素值取值 1(白色),值低​​于100 取值 0(黑色) 所以任何建议请(对不起我的英语不好)

我的代码:

`将 numpy 导入为 np 导入cv2

image = cv2.imread('Image3.png', 0)




dimension = image.shape
height = dimension[0]
width = dimension[1]

#finalimage = np.zeros((height, width))
for i in  range(height) :
    for j in  range(width):
        
        if (image[i, j] > 100):
            image[i][j] = [1]  
        else:
            image[i][j] = [0]

cv2.imshow('binarizedImage',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

  • 您可能想使用 255 而不是 1,但是这段代码有什么地方不能正常工作吗?
  • 是的,当我执行程序时,它显示一个黑色图像

标签: python opencv computer-vision


【解决方案1】:

您可以尝试使用 OpenCV 函数 cv2.threshold 进行二值化。

import cv2
img = cv2.imread('Image3.png', cv2.IMREAD_GRAYSCALE)
thresh = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)[1]
cv2.imshow('binarizedImage',thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

【讨论】:

    【解决方案2】:

    我想你只想使用 np.where():

    import numpy as np
    image = np.array([[200, 50, 200],[50, 50 ,50],[10, 255, 10]]) #this will be your image instead
    
    In [11]: image
    Out[11]: 
    array([[200,  50, 200],
           [ 50,  50,  50],
           [ 10, 255,  10]])
    
    In [12]: np.where(image > 100, 1, 0)
    Out[12]: 
    array([[1, 0, 1],
           [0, 0, 0],
           [0, 1, 0]])
    

    【讨论】: