Python OpenCV通过灰度平均值进行二值化处理以减少像素误差

在这里插入图片描述

前言

前提条件

相关介绍

  • Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。

实验环境

  • Python 3.x (面向对象的高级语言)

通过灰度平均值进行二值化处理以减少像素误差

  • 背景:同一物体(黑色异物)但不同亮度大小的图片,单纯地使用固定阈值的二值化处理,所得到的物体(黑色异物)的像素个数误差较大,实验表明,通过灰度平均值进行二值化处理,可以有效地减少像素个数的误差

  • 在这里插入图片描述

  • 在这里插入图片描述

固定阈值二值化

代码实现

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FriendshipT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值