如何将灰度图像转换为二进制图像并逆转python中的过程? [英] How to convert grayscale image to binary image and reverse the process in python?

查看:77
本文介绍了如何将灰度图像转换为二进制图像并逆转python中的过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务将灰度图像转换为二进制图像,然后将其恢复为原始格式.我正在使用opencv中的阈值函数将灰度图像转换为二进制图像.有什么方法可以将二进制图像转换为灰色图像吗?

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. 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-通过导入cv2读取灰度图像

i- read a grayscale image by importing cv2

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

ii-将灰度图像转换为二进制图像

ii- convert grayscale image to binary

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

使用Otsu的方法自动从图像中确定阈值,或者如果您已经知道阈值,则可以使用:

which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:

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

iii-保存

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

这篇关于如何将灰度图像转换为二进制图像并逆转python中的过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆