安装
linux & win
核心库
#仅对当前用户安装 --user; 否则为全局安装
pip3 install --user opencv-python==3.4.2.16 --index-url https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host https://pypi.tuna.tsinghua.edu.cn
贡献库
pip3 install --user opencv-contrib-python==3.4.2.16 --index-url https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host https://pypi.tuna.tsinghua.edu.cn
使用
读取与显示
import cv2
im = cv2.imread("2.jpg",1) #1为彩色图 0为灰度图
#返回np.ndarray
cv2.imshow("win",im) #显示,非阻塞
#转为灰度图
im_gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
cv2.imshow("win1",im_gray)
cv2.waitKey() #阻塞,等待用户键盘输入,显示图片
cv2.destroyAllWindows() #销毁窗口
改变通道
import cv2
im = cv2.imread("./images/opencv2.png",1)
#取出一个蓝色通道 cv2中 BGR 顺序
b = im[:,:,0] # 宽、高、通道
#单通道为灰度图,且该通道变为白色,其他通道变为灰色
cv2.imshow("blue",b)
#将蓝色通道置为0
im[:,:,0] = 0
cv2.imshow("blue0",im)
cv2.waitKey()
cv2.destroyAllWindows()
直方图均衡化
- 灰度图像的直方图均衡化
import cv2
import numpy as np
from matplotlib import pyplot as plt
im = cv2.imread("images/sunrise.jpg",0)
cv2.imshow("origin",im)
#均衡化
im_eq = cv2.equalizeHist(im) #提高整体对比度
cv2.imshow("im_eq",im_eq)
#绘制原图的直方图
plt.subplot(2,1,1)
plt.hist(im.ravel(),256,[0,256],label="origin")
#绘制均衡化的直方图
plt.subplot(2,1,2)
plt.hist(im_eq.ravel(),256,[0,256],label="equalized")
plt.show()
key = cv2.waitKey()
print("current key:",key)
cv2.destroyAllWindows()
具体效果如下:
让单通道像素点的灰度级,分布的更加的均衡,提高整体对比度。
- 彩色图的直方图均衡化
取出一个通道,均衡化
# 彩色图的直方图的均衡化 BGR==>转为===>YUV
im = cv2.imread("images/sunrise.jpg") # 默认为1彩色图
cv2.imshow("origin",im)
yuv = cv2.cvtColor(im,cv2.COLOR_BGR2YUV)
#取出亮度通道,进行均衡化
yuv[:,:,0] = cv2.equalizeHist(yuv[:,:,0])
#YUV--->BGR 为了显示
bgr = cv2.cvtColor(yuv,cv2.COLOR_YUV2BGR)
cv2.imshow("bgr",bgr) #只适合显示RGB的图像
key = cv2.waitKey()
print("current key:",key)
cv2.destroyAllWindows()
二值化
im = cv2.imread("images/lena.jpg",0)
cv2.imshow("origin",im)
#二值化,设置一个阈值,大于则为255,返回(阈值,二值化的二维数组),源不变
threshold,im_binary = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
print(im_binary)
#反二值化 只有一处不同
threshold,inverse_binary = cv2.threshold(im,127,255,cv2.THRESH_BINARY_INV)
cv2.imshow("im_binary",im_binary)
cv2.imshow("inverse_binary",inverse_binary)
上一篇:图像处理基础 下一篇