OpenCV Python – 如何将彩色图像转换为二进制图像?

我们使用 cv2.threshold() 将灰度图像转换为二进制图像。要将彩色图像转换为二进制图像,我们首先使用 cv2.cvtColor() 将彩色图像转换为灰度图像,然后在灰度图像上应用 cv2.threshold()。

步骤

可以按照以下给定的步骤将彩色图像转换为二进制图像-

  • 导入所需的库。在以下所有示例中,所需的 Python 库是 OpenCV。确保您已经安装了它。

  • 使用 cv2.imread() 读取输入图像。使用此方法读取的 RGB 图像采用 BGR 格式。(可选)将读取的 BGR 图像分配给 img。

  • 现在使用 cv2.cvtColor() 函数将此 BGR 图像转换为灰度图像,如下所示。(可选)将转换后的灰度图像指定为灰度。

  • 在灰度图像灰色上应用阈值 cv2.threshold() 以将其转换为二进制图像。调整第二个参数(threshValue)以获得更好的二进制图像。

  • 显示转换后的二进制图像。

让我们看一些例子,以便清楚地理解这个问题。

在下面的示例中,我们将使用以下图像作为输入文件

在这个 Python 程序中,我们将彩色图像转换为二进制图像。我们还显示二进制图像。

 

# import required libraries import cv2 # load the input image img = cv2.imread('architecture1.jpg') # convert the input image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert grayscale to binary image ret,thresh = cv2.threshold(gray,70,255,0) # Display the Binary Image cv2.imshow("Binary Image", thresh) cv2.waitKey(0) cv2.destroyAllWindows()

输出

When you run the above program, it will produce the following output window showing the binary image.

 

 

在此示例中,我们将彩色图像转换为二进制图像。我们还显示原始图像、灰度图像和二进制图像。

 

# import required libraries import cv2 import matplotlib.pyplot as plt # load the input image img = cv2.imread('architecture1.jpg') # convert the input image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert grayscale to binary image ret,thresh = cv2.threshold(gray,70,255,0) # convert BGR to RGB to display using matplotlib imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # display Original, Grayscale and Binary Images plt.subplot(131),plt.imshow(imgRGB,cmap = 'gray'),plt.title('Original Image'), plt.axis('off') plt.subplot(132),plt.imshow(gray,cmap = 'gray'),plt.title('Grayscale Image'),plt.axis('off') plt.subplot(133),plt.imshow(thresh,cmap = 'gray'),plt.title('Binary Image'),plt.axis('off') plt.show()

输出

当您运行上述程序时,它将产生以下输出窗口,显示原始,灰度和二进制图像。

 

请注意灰度图像和二进制图像之间的区别。二进制图像只有两种颜色:白色和黑色。二进制图像的像素值为 0(黑色)或 255(白色)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值