二值化是将图像使用黑和白两种颜色表示的方法。
我们将灰度的阈值设置为
128
128
128来进行二值化,即:
y
=
{
0
(
if
y
<
128
)
255
(
else
)
y=\begin{cases}0& (\text{if}\quad y < 128) \\255& (\text{else})\end{cases}
y={0255(ify<128)(else)
代码实现:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 14:53:28 2020
@author: 陨星落云
"""
import imageio
# 读取图像
img = imageio.imread("Gray.jpg")
h,w = img.shape
# 二值化
thresh_img = img.copy().reshape(h*w)
for i in range(h*w):
if thresh_img[i] < 128:
thresh_img[i] = 0
else:
thresh_img[i] = 255
thresh_img = thresh_img.reshape(h,w)
# 保存结果
imageio.imsave("thresh_img.jpg", thresh_img)
结果: