简体   繁体   English

如何将灰度图像转换为二进制图像并在python中反转过程?

[英]How to convert grayscale image to binary image and reverse the process in python?

I have a task to convert a grayscale image to binary and then take it back to its original form.我有一项任务是将灰度图像转换为二进制,然后将其恢复为原始形式。 I am using threshold function from opencv to convert the gray image into a binary.我正在使用 opencv 的阈值函数将灰度图像转换为二进制。 Is there any way to reconvert the binary image to the gray one?有没有办法将二值图像重新转换为灰色图像?

You can follow the below steps to convert gray scale image to binary image :您可以按照以下步骤将灰度图像转换为二进制图像:

i- read a grayscale image by importing cv2 i- 通过导入 cv2 读取灰度图像

import cv2
im_gray = cv2.imread('path_of_grayscale_image.png', cv2.CV_LOAD_IMAGE_GRAYSCALE)

ii- convert grayscale image to binary ii- 将灰度图像转换为二进制

(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:它使用 Otsu 的方法从图像中自动确定阈值,或者如果您已经知道阈值,则可以使用:

thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]

iii- save iii-保存

cv2.imwrite('binary_image.png', im_bw)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM