Python——OpenCV库的学习(十三):黑白统计

笔记和用法都在代码注释中:

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread('666.jpg',0)  #0代表灰度图
img = cv.resize(img,(500,500))
hist = cv.calcHist([img],[0],None,[256],[0,256])
print(hist.shape)
#
# plt.hist(img.ravel(),256)
# plt.show()

# cv2.calcHist(images,channels,mask,histSize,ranges)
# Cv2.xxxxxxxxxx(图像、通道、掩膜、组织尺寸、范围)
#
# images:原图像图像格式为uint8或float32。当传入函数时应用中括号括来例如[img]
# channels:同样用中括号括来它会告函数我们统幅图像的直方图。
# omask:掩模图像。统整幅图像的直方图就把它为None。但是如果你想统图像某一分的直方图的你就制作一个掩模图像并使用它.
# histSize:BIN的数目。也应用中括号括来
# ranges:像素值范围常为[0256]

# -------------------------------------三原色通道统计分别打印!!!!
# img = cv.imread('666.jpg')
# color = ('b','g','r')
# for n,m in enumerate(color):
#     hist = cv.calcHist([img],[n],None,[256],[0,256])
#     plt.plot(hist,color = m)
#     plt.xlim([0,256])
#     plt.show()

# 创建mast
mask = np.zeros(img.shape[:2],np.uint8)   #np.uint8 就是 0——255,
mask[100:1000,100:1800] = 255      #(x1:y1) ,(x2:y2) x1和x2是边框距离, y1(h) 和 y2(w) 是掩码大小

masked_img = cv.bitwise_and(img,img,mask=mask)  #与操作

hist_full = cv.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv.calcHist([img],[0],mask,[256],[0,256])

plt.subplot(221),plt.imshow(img,'gray')
plt.subplot(222),plt.imshow(mask,'gray')
plt.subplot(223),plt.imshow(masked_img,'gray')
plt.subplot(224),plt.plot(hist_full),plt.plot(hist_mask)
plt.xlim([0,256])
plt.show()

#直方图均衡化 :
# 第一种:没有处理————————:
plt.hist(img.ravel(),256);  #蓝色
# plt.show()

equ = cv.equalizeHist(img)   #均衡化处理!!! (橙色!!!)
plt.hist(equ.ravel(),256)
plt.show()                   #直方图展示1!!

# 接下来: 对比图片,看看图片直方化的结果:  (均衡化之后,感觉图像更亮了!!!【但是会丢失一些细节!!】)
# res = np.hstack((img,equ))   #左边的是原图像,右边是均衡化的!!!
# cv.imshow('res',res)
# cv.waitKey(0)
# cv.destroyAllWindows()

#均衡化优化处理 : 做均衡化局部处理:
clahe = cv.createCLAHE(clipLimit = 2.0, tileGridSize = (8,8))   #对图像做局部处理!!!

res_clahe = clahe.apply(img)
res = np.hstack((img,equ,res_clahe))  #结果:这样不仅像素均衡,并且图像不会损失太多细节!!
cv.imshow('res',res)
cv.waitKey(0)
cv.destroyAllWindows()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Pan_peter

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

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

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

打赏作者

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

抵扣说明:

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

余额充值