【计算机视觉(7)】-图片阈值处理的代码实现

时间:2024-06-08 16:12:01

全局阈值处理的代码:

import cv2                     
import matplotlib.pyplot as plt
  
image = cv2.imread("img/300.jpg")     
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 灰度化  
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) # 二值化  
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV) # 反二值化  
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC) # 截断阈值处理  
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO) # 低于阈值处理  
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV) # 超出阈值处理  
  
titles = ["original", "BINARY", "BINARY_INV", "TRUNC", "TOZERO", "TOZERO_INV"]  
images = [image, thresh1, thresh2, thresh3, thresh4, thresh5]  
  
for i in range(6):  
    plt.subplot(2, 3, i + 1), plt.imshow(images[i], "gray")  
    plt.title(titles[i])  
plt.show()  

代码实现效果如下:
在这里插入图片描述
局部阈值处理的代码:

import cv2  
import numpy as np     
    
image = cv2.imread("img/300.jpg") # 导入图片
image = cv2.resize(image,(500,500))   
img_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)  
ret, Otsu_thresh_img = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) # Otsu寻找最佳阈值进行二值化  
adaptive_thresh_img = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 5) # 均值滤波进行局部阈值化处理  

res = np.hstack((Otsu_thresh_img, adaptive_thresh_img))  

cv2.imshow("res", res)  
cv2.waitKey(0)  
cv2.destroyAllWindows() 

代码实现效果如下:
在这里插入图片描述

相关文章