python数字图像处理(基于阈值化的图像分割)

代码如下:

import cv2 as cv
import numpy as np  
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号 
#读取图像
img = cv.imread("./imgs/chep.png")
rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
#灰度化处理图像
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#灰度直方图
# plt.figure()
# plt.hist(gray_img.ravel(),256)
# plt.show()
#固定阈值法、OTSU、自适应
ret,thresh1=cv.threshold(gray_img,55,255,cv.THRESH_BINARY)
ret2,thresh2=cv.threshold(gray_img,0,255,cv.THRESH_OTSU)
thresh3=cv.adaptiveThreshold(gray_img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,25,0)
thresh4=cv.adaptiveThreshold(gray_img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,91,0)
#显示效果
titles=['rgb','gay','thresh_55','OTSU','adp_25','adp_91']

images=[rgb_img,gray_img,thresh1,thresh2,thresh3,thresh4]

plt.figure(figsize=(10,3))
for i in range(6):
    plt.subplot(2,3,i+1)
    plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.axis('off')
plt.show()

结果如下:

python数字图像处理(基于阈值化的图像分割)_第1张图片

 

你可能感兴趣的:(数字图像处理,python,opencv,计算机视觉,人工智能)