Python OpenCV通过灰度平均值进行二值化处理以减少像素误差
前言
前提条件
相关介绍
实验环境
通过灰度平均值进行二值化处理以减少像素误差
固定阈值二值化
代码实现
import cv2
import numpy as np
# 图像显示函数
def show(name, img):
cv2.namedWindow(name, 0) # 用来创建指定名称的窗口,0表示CV_WINDOW_NORMAL
# cv2.resizeWindow(name, img.shape[1], img.shape[0]); # 设置宽高大小为640*480
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def count_pix_nums(img_path):
img=cv2.imread(img_path,0)
ret, thresh = cv2.threshold(img,60,255, cv2.THRESH_BINARY_INV)
pix_nums = np.count_nonzero(thresh)
return pix_nums
if __name__=="__main__":
light_pix_nums = count_pix_nums('imgs/light.jpg')
dark_pix_nums = count_pix_nums('imgs/dark.jpg')
print("亮度较大的图,物体(黑色异物)像素个数为:",light_pix_nums)
print("亮度较小的图,物体(黑色异物)像素个数为:",dark_pix_nums)
亮度较大的图,物体(黑色异物)像素个数为: 3558
亮度较小的图,物体(黑色异物)像素个数为: 3693
灰度平均值二值化
代码实现
import cv2
import numpy as np
# 图像显示函数
def show(name, img):
cv2.namedWindow(name, 0) # 用来创建指定名称的窗口,0表示CV_WINDOW_NORMAL
# cv2.resizeWindow(name, img.shape[1], img.shape[0]); # 设置宽高大小为640*480
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def count_pix_nums(img_path):
img=cv2.imread(img_path,0)
mean_gray_value = np.mean(img)
threshold_value_bias = 60
threshold_value = mean_gray_value - threshold_value_bias
ret, thresh = cv2.threshold(img,threshold_value,255, cv2.THRESH_BINARY_INV)
pix_nums = np.count_nonzero(thresh)
return pix_nums
if __name__=="__main__":
light_pix_nums = count_pix_nums('imgs/light.jpg')
dark_pix_nums = count_pix_nums('imgs/dark.jpg')
print("亮度较大的图,物体(黑色异物)像素个数为:",light_pix_nums)
print("亮度较小的图,物体(黑色异物)像素个数为:",dark_pix_nums)
亮度较大的图,物体(黑色异物)像素个数为: 3950
亮度较小的图,物体(黑色异物)像素个数为: 3948