参考了:https://blog.csdn.net/firemicrocosm/article/list/2?t=1
在此表示感谢!
基本图像操作函数:
图像的读取,保存,RGB分层
# coding= utf-8 #or gbk 这样才能使用中文
import cv2
import numpy as np
**# 读取图像**
img = cv2.imread("lena.jpg", 1) # 读取彩色图像
img_g = cv2.imread("lena.jpg", 0) # 读取灰度图像
**# 复制图像**
img_copy = img.copy()
**# 获取图像的尺寸及通道数**
width, height, ch = img.shape
print(width, height, ch)
print img.size # 打印像素数目
# 彩色通道的拆分与合并,速度较慢
b, g, r = cv2.split(img)
img = cv2.merge([b,g,r])
# 采用类似 matlab 中的下标索引方式,速度比较快
# 分离彩色通道,顺序是BGR,与 matlab的RGB 不同
B = img[:, :, 0]
G = img[:, :, 1]
R = img[:, :, 2]
# 调整RGB通道的顺序
img_RGB = img.copy()
img_RGB[:, :, 0] = R
img_RGB[:, :, 1] = G
img_RGB[:, :, 2] = B
# 采用类似 matlab 显示多个坐标轴的形式并行显示,比较方便
# 由于 matlab 是按照RGB顺序显示的,所以需要将原图像的顺序重调一下
plt.subplot(231), plt.imshow(img,'gray'), plt.title("img_BGR")
plt.subplot(232), plt.imshow(img_RGB, "gray"), plt.title("Img_RGB")
plt.subplot(233), plt.imshow(B, "gray"), plt.title("B")
plt.subplot(234), plt.imshow(G, "gray"), plt.title("G")
plt.subplot(235), plt.imshow(R, "gray"), plt.title("R")
plt.show()
# 利用NumPy 创建空的图像
emptyImage = np.zeros(img.shape, np.uint8) #参数形状,位图深度
# 保存图像
cv2.imwrite("lena_copy.jpg", img_copy)
# 颜色变换
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 大小尺度变换
img_resize = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
cv2.namedWindow("lena_rgb")
cv2.namedWindow("lena_gray")
cv2.namedWindow("emptyImage")
cv2.namedWindow("gray")
cv2.namedWindow("resize")
cv2.imshow("lena_rgb", img)
cv2.imshow("lena_gray", img_g)
cv2.imshow("emptyImage", emptyImage)
cv2.imshow("gray", img_gray)
cv2.imshow("resize", img_resize)
cv2.waitKey(0) #让窗口等待(不加则会一闪而过)
cv2.destroyAllWindows()
图像滤波算子
平滑与锐化
#coding:utf8
import cv2
import numpy as np
from matplotlib import pyplot as plt
####################################
# 将图像的BGR顺序纠正为RGB
def bgr2rgb(src):
img = src.copy()
img[:, :, 0] = src[:, :, 2]
img[:, :, 2] = src[:, :, 0]
return img
######################################
# 图像平滑
img = cv2.imread("1.jpg")
# 创建滤波器
k = 9
kernel = np.ones((k, k), np.float32) / k ** 2
print kernel
# 使用自滤波器进行滤波
# cv.Filter2D(src, dst, kernel, anchor=(-1, -1))
# ddepth –desired depth of the destination image;
# if it is negative, it will be the same as src.depth();
# the following combinations of src.depth() and ddepth are supported:
# src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F
# src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F
# src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F
# src.depth() = CV_64F, ddepth = -1/CV_64F
# when ddepth = -1, the output image will have the same depth as the source.
img_average = cv2.filter2D(img, -1, kernel)
# 使用blur()函数进行均值滤波
img_blur = cv2.blur(img, (k, k))
# 高斯平滑
img_gaussian = cv2.GaussianBlur(img, (k, k), 3)
# 也可以自己创建一个高斯核
# kernel_g = cv2.getGaussianKernel(k, 5)
# img_gaussian = cv2.filter2D(img,-1,kernel_g)
# print kernel_g.shape
# 中值滤波
# img_median = cv2.medianBlur(img_noise,k)
# plt.subplot(121),plt.imshow(img_noise,'gray'),plt.title("噪声图像")
# plt.subplot(122),plt.imshow(img_median,'gray'),plt.title("中值滤波后的图像")
# plt.show()
# 双边滤波
# cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace)
# d – Diameter of each pixel neighborhood that is used during filtering.
# If it is non-positive, it is computed from sigmaSpace
# 9 邻域直径,两个75 分别是空间高斯函数标准差,灰度值相似性高斯函数标准差
img_new = cv2.imread("Airplane.jpg")
img_bf = cv2.bilateralFilter(img_new, 9, 75, 75)
# 平滑滤波结果
plt.subplot(221), plt.imshow(bgr2rgb(img), "gray"), plt.title("Original")
plt.xticks([]), plt.yticks([]) # 去掉坐标轴刻度
plt.subplot(222), plt.imshow(bgr2rgb(img_average), "gray"), plt.title("average_filtering")
plt.xticks([]), plt.yticks([])
plt.subplot(223), plt.imshow(bgr2rgb(img_blur), "gray"), plt.title("blur_filtering")
plt.xticks([]), plt.yticks([])
plt.subplot(224), plt.imshow(bgr2rgb(img_gaussian), "gray"), plt.title("gaussian_filtering")
plt.xticks([]), plt.yticks([])
plt.show()
# 双边滤波结果
plt.subplot(121), plt.imshow(bgr2rgb(img_new), "gray"), plt.title("Original")
plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(bgr2rgb(img_bf), "gray"), plt.title("bilateralFilter")
plt.xticks([]), plt.yticks([])
plt.show()
##锐化
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) #转化为灰度图
# sobel 算子
# cv2.Sobel(src,ddepth,dx,dy,dst=None,ksize,scale,delta)
# dx = 1 对x方向求梯度
# dy = 1 对y方向求梯度
img_sobel_x = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=3)
img_sobel_y = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=3)
# Laplace 算子
img_laplace = cv2.Laplacian(img_gray, cv2.CV_64F, ksize=3)
# Canny 算子
img_canny = cv2.Canny(img_gray, 100 , 150)
plt.subplot(231), plt.imshow(img_gray, "gray"), plt.title("Original")
plt.subplot(232), plt.imshow(img_sobel_x, "gray"), plt.title("Sobel_x")
plt.subplot(233), plt.imshow(img_sobel_y, "gray"), plt.title("Sobel_y")
plt.subplot(234), plt.imshow(img_laplace, "gray"), plt.title("Laplace")
plt.subplot(235), plt.imshow(img_canny, "gray"), plt.title("Canny")
plt.show()
直方图
# coding:utf-8
import cv2
import numpy as np
from matplotlib import pyplot as plt
file = "E:\python\Python Project\opencv_showimage\images\lena.jpg"
img = cv2.imread(file, 0)
# OpenCV 函数
hist = cv2.calcHist([img],[0],None,[256],[0,256])
plt.plot(hist, color='r')
plt.xlim([0,256])
plt.show()
# Numpy 函数
# ravel 是将矩阵拉成列向量
plt.hist(img.ravel(),256,[0,256])
plt.xlim([0,256])
plt.show()
# 彩色图像直方图
img = cv2.imread(file,1)
color = ('b','g','r')
for i,col in enumerate(color):
hist = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(hist,color=col)
plt.xlim([0,256])
plt.show()
# 设置掩膜,只统计掩膜区域的直方图
# 创造一个掩膜
img = cv2.imread(file,0)
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300,100:400] = 255
masked_img = cv2.bitwise_and(img,img,mask=mask)
hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv2.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,color='r'),plt.plot(hist_mask,color='g'),plt.xlim([0,256])
plt.show()
# 直方图均衡化
img = cv2.imread(file, 0)
equ = cv2.equalizeHist(img)
res = np.hstack((img, equ)) # 将图像拼在一起
cv2.namedWindow("equ")
cv2.imshow("equ", res)
cv2.waitKey(0)
cv2.destroyAllWindows()
# CLAHE 有限对比适应性直方图均衡化,效果更好
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl1 = clahe.apply(img)
res1 = np.hstack((equ, cl1)) # 将图像拼在一起
cv2.imshow("CLAHE", res1)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 2D 直方图
img = cv2.imread(file, 1)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([img_hsv],[0,1],None,[180,256],[0,180,0,256])
plt.imshow(hist, interpolation='nearest'), plt.xlabel("S"), plt.ylabel("H")
plt.show()
RGB颜色直方图:
直方图均衡化:增强对比度
有限对比适应性直方图均衡化,效果更好: