效果展示
理论部分
-
灰度:表示图像像素明暗程度的数值,也就是黑白图像中点的颜色深度。范围一般为0-255。白色为255,黑色为0。
-
通道:把图像分解成一个或多个颜色成分:
-
单通道:一个像素点只需一个数值表示,只能表示灰度,0为黑色(灰度化和二值化)
-
三通道:把图像分为红绿蓝三个通道,可以表示彩色(RGB模式)
-
四通道:在RGB基础上加上alpha(透明度)通道,alpha=0表示全透明
-
RGB转化为灰度图
- 浮点算法:Gray = R0.3 +G0.59 + B0.11
- 整数算法:Gray = (R30 + G59 + B11) / 100
-
二值化
- Step1:灰度化:img_gray = rgb2gray(img)
- Step2:二值化(阈值随意设置,这里设置为0.5):
rows, cols = img_gray.shape img_binary = np.zeros([h,w],img.dtype) for i in range(rows): for j in range(cols): img_binary[i,j] = int(img_gray[i,j]+0.5)
代码部分
- 使用库
- opencv:安装使用pip install opencv-python,使用时用 import cv2
- matplotlib:安装使用pip install matplotlib,使用时用 import matplotlib.pyplot as plt
- skimage:安装使用pip install scikit-image,使用时用 import skimage
"""
@author: Hanley-Yang
彩色图像的二值化
"""
from skimage.color import rgb2gray
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2
#灰度化处理
img = cv2.imread("shangri-la.jpg")
h,w = img.shape[:2]
img_gray = np.zeros([h,w],img.dtype)
# 遍历灰度化每个像素值
# for i in range(h):
# for j in range(w):
# init = img[i,j]
# img_gray[i,j] = int((init[0]*0.11 + init[1]*0.59 + init[2]*0.3) / 255)
img_gray = rgb2gray(img)
#二值化
rows, cols = img_gray.shape
img_binary = np.zeros([h,w],img.dtype)
for i in range(rows):
for j in range(cols):
img_binary[i,j] = int(img_gray[i,j]+0.5)
print("---image gray----")
print(img_gray)
#img_binary = np.where(img_gray >= 0.5, 1, 0) #也可使用该方法二值化
print("---image binary---")
print(img_binary)
print(img_binary.shape)
#显示原始图片在画布上方
plt.subplot(211)
img = plt.imread("shangri-la.jpg")
plt.imshow(img)
#显示二值化图片在画布下方
plt.subplot(212)
plt.imshow(img_binary, cmap='gray')
plt.show()