文章目录
- 前言
- 一、Python全局128
- 二、Python全局均值
- 三、Python全局OTSU
- 四、FPGA全局128
- 总结
前言
为什么要进行图像二值化,rgb图像有三个通道,处理图像的计算量较大,二值化的图像极大的减少了处理图像的计算量。即便从彩色图像转成了二值化图像,也不影响对物体的识别。本章开始讲解图像二值化。Python包含全局128、全局均值、大津阈值法(OTSU);FPGA只做全局128的讲解。
一、Python全局128
import numpy as np
import matplotlib.pyplot as plt
img = plt.imread("lenna.png")
gray = 0.299 * img[:, :, 0] + 0.587 * img[:, :, 1] + 0.114 * img[:, :, 2]
gray = gray * 255#图像是[0-1]--->[0-255]
bin_image = np.where(gray >= 128, 255, 0)#全局二值化
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 2, 1)
ax.set_title("gray image")
ax.set_xlabel("width")
ax.set_ylabel("height")
plt.imshow(gray, cmap="gray")
ax = fig.add_subplot(1, 2, 2)
ax.set_title("binary image")
ax.set_xlabel("width")
ax.set_ylabel("height")
plt.imshow(bin_image, cmap="gray")
二、Python全局均值
mean_image = np.where(gray > np.mean(gray), 255, 0)#全局均值
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 2, 1)
ax.set_title("gray image")
ax.set_xlabel("width")
ax.set_ylabel("height")
plt.imshow(gray, cmap="gray")
ax = fig.add_subplot(1, 2, 2)
ax.set_title("mean image")
ax.set_xlabel("width")
ax.set_ylabel("height")
plt.imshow(mean_image, cmap="gray")
三、Python全局OTSU
OTSU是阈值分割中一种常用的算法,它可以根据图像自动生成最佳分割阈值。 OTSU的核心思想是类间方差最大化。
- 初始化一个阈值T0,将图像分为前景f和背景b;
- 图像像素点个数为图像N=height x width,前景像素个数Nf,背景像素个数Nb;
- 图像灰度等级L-1(0~255=256),每个灰度等级像素个数Ni,满足以下公式:
P f = ∑ i = 0 i =