opencv常用

# -*- coding: utf-8 -*-
"""
Created on Sat Jan  5 15:44:42 2019

@author: oucbu
"""
 
import cv2
import numpy as np
from matplotlib import pyplot as plt

img=cv2.imread('1.jpg',0)#0为灰度图
cv2.imwrite('2.jpg',img,[int(cv2.IMWRITE_JPEG_QUALITY), 5])#bmp、jpg、png、tiff
cv2.imwrite('3.png',img,[int(cv2.IMWRITE_PNG_COMPRESSION),9])
cv2.namedWindow("Image")
cv2.imshow("Image",img)


emptyImage=np.zeros(img.shape,np.uint8)

emptyImage2=img.copy()
emptyImage3=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)


plt.imshow(img,'gray')
plt.xticks([])
plt.yticks([])
plt.show()

img2=np.zeros((512,512),np.uint8)
cv2.line(img2,(0,0),(511,511),255,5)
plt.imshow(img2,'gray')

img3=np.zeros((512,512,3),np.uint8)
cv2.line(img3,(0,511),(511,0),(0,155,0),5)
plt.imshow(img3,'brg')#RGB

img4=np.zeros((512,512,3),np.uint8)
cv2.rectangle(img4,(20,20),(200,200),(255,0,0),10)
cv2.circle(img4,(200,200),50,(55,255,155),10)
cv2.ellipse(img4,(256,256),(150,100),10,0,360,(250,250,0),-1)#偏转10,画0到360度,
plt.imshow(img4,'brg')

img = cv2.imread('1.jpg')
H = np.float32([[1,0,100],[0,1,50]])
rows,cols = img.shape[:2]#取图片的长宽,[:3]取长、宽、通道
res = cv2.warpAffine(img,H,(rows,cols)) #需要图像、变换矩阵、变换后的大小
plt.subplot(121)
plt.imshow(img)
plt.subplot(122)
plt.imshow(res)

#放大两倍 方法一
res1=cv2.resize(img,None,fx=2,fy=2,interpolation=cv2.INTER_CUBIC)
#方法二
height,width=img.shape[:2]
res2=cv2.resize(img,(2*width,2*height),interpolation=cv2.INTER_CUBIC)
plt.subplot(131)
plt.imshow(img)
plt.subplot(132)
plt.imshow(res1)
plt.subplot(133)
plt.imshow(res2)


#仿射变换  warpAffine
rows,cols=img.shape[:2]
M=cv2.getRotationMatrix2D((rows/2,cols/2),45,1)#旋转中心,旋转角度,缩放比例
res=cv2.warpAffine(img,M,(rows,cols))
plt.imshow(res)


rows,cols=img.shape[:2]
pts1=np.float32([[50,50],[200,50],[50,200]])#3个点
pts2=np.float32([[10,100],[200,50],[100,250]])
M=cv2.getAffineTransform(pts1,pts2)
M1=cv2.getAffineTransform(pts2,pts1)#变完之后换一下位置,还原不了图像
res=cv2.warpAffine(img,M,(rows,cols))
res2=cv2.warpAffine(res,M1,(rows,cols))
plt.imshow(res2)

rows,cols=img.shape[:2]
pts1=np.float32([[100,200],[300,200],[100,500],[300,500]])#4个点
pts2=np.float32([[0,0],[200,0],[0,300],[200,300]])
M=cv2.getPerspectiveTransform(pts1,pts2)
res=cv2.warpPerspective(img,M,(400,400))#(400,400)是原始图像中心点
plt.imshow(res)
cv2.waitKey(0)
cv2.destroyAllWindows()

img = cv2.imread('1.jpg',0) #直接读为灰度图像
#大于127,则赋值为255
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)#黑白
#返回阈值,变换后的图像
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)#黑白反转
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)#
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
titles = ['img','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img,thresh1,thresh2,thresh3,thresh4,thresh5]
for i in range(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()


img = cv2.imread('1.jpg',0) #直接读为灰度图像
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
cv2.THRESH_BINARY,11,2) #换行符号 \
th3 = cv2.adaptiveThreshold(
        img,255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,#均值或者高斯
        cv2.THRESH_BINARY,#cv2.THRESH_BINARY 或者 cv2.THRESH_BINARY_INV
        11,#Block size:规定领域大小
        2) #阈值等于均值或者加权值减去这个常数
#就是说没一个框的阈值都不同。把一个方形区域的平均灰度值作为阈值
images = [img,th1,th2,th3]
plt.figure()
for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.show()

img = cv2.imread('1.jpg',0) #直接读为灰度图像
#简单滤波
ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
#Otsu 滤波 尤其灰度直方图具有双峰的情况
ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
print (ret2)
plt.figure()
plt.subplot(221),plt.imshow(img,'gray')
plt.subplot(222),plt.hist(img.ravel(),256)#.ravel方法将矩阵转化为一维
plt.subplot(223),plt.imshow(th1,'gray')
plt.subplot(224),plt.imshow(th2,'gray')

#卷积运算,滤波
img = cv2.imread('1.jpg',0) #直接读为灰度图像
img1 = np.float32(img) #转化数值类型
kernel = np.ones((5,5),np.float32)/25

dst = cv2.filter2D(img1,-1,kernel)#图像深度-1表示生产图像与原图像一致
#卷积核,一个单通道浮点型矩阵
#cv2.filter2D(src,dst,kernel,auchor=(-1,-1))函数:

plt.figure()
plt.subplot(1,2,1),plt.imshow(img1,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(dst,'gray')

# 滤波解析
#https://blog.csdn.net/xw20084898/article/details/21822565

#均值滤波
blur = cv2.blur(img,(3,5))#模板大小3*5 
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(blur,'gray')

#高斯滤波
for i in range(2000): #添加点噪声
    temp_x = np.random.randint(0,img.shape[0])
    temp_y = np.random.randint(0,img.shape[1])
    img[temp_x][temp_y] = 255
blur = cv2.GaussianBlur(img,(5,5),0)#必须是奇数
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(blur,'gray') 

#中值滤波  去椒盐噪声
for i in range(2000): #添加点噪声
    temp_x = np.random.randint(0,img.shape[0])
    temp_y = np.random.randint(0,img.shape[1])
    img[temp_x][temp_y] = 255

blur = cv2.medianBlur(img,5)#必须是奇数
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(blur,'gray') 

#双边滤波 去噪声,存边界
for i in range(2000): #添加点噪声
    temp_x = np.random.randint(0,img.shape[0])
    temp_y = np.random.randint(0,img.shape[1])
    img[temp_x][temp_y] = 255

blur = cv2.bilateralFilter(img,9,75,75)#滤波领域直径,空间高斯函数标准差,灰度值相似性标准差
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(blur,'gray')


#形态学使用二值图进行边界提取,骨架提取,孔洞填充,角点提取,图像重建等等。常用的形态学操作时腐蚀与膨胀,
#在他们的基础上演变出一些变体,包括开运算、闭运算、梯度等等。形态学一般是对二值图像进行的操作。

#腐蚀
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)#先变成二值图,膨胀腐蚀针对于白色区域,所以要进行反转
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(thresh1,kernel,1)
plt.subplot(2,2,1),plt.imshow(thresh1,'gray'),plt.title('original')
plt.subplot(2,2,2),plt.imshow(erosion,'gray'),plt.title('erosion')


#膨胀
dilation = cv2.dilate(thresh1,kernel,1)
plt.subplot(2,2,3),plt.imshow(thresh1,'gray'),plt.title('original')
plt.subplot(2,2,4),plt.imshow(dilation,'gray'),plt.title('dilation')

#先进行腐蚀再进行膨胀的运算就是开运算
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(erosion,'gray')

#闭运算
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(erosion,'gray')

#形态学梯度
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((5,5),np.uint8)
closing= cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(closing,'gray')

#礼帽
#原始图像与其进行开运算后的图像进行一个差。
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((5,5),np.uint8)
closing= cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(closing,'gray')

#黑帽
#原始图像与其进行闭运算后的图像进行一个差。
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((5,5),np.uint8)
closing= cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr
plt.subplot(1,2,2),plt.imshow(closing,'gray')


#边缘提取
#sobel (x方向,y方向,xy方向)   laplacian 
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)#默认ksize=3
sobely = cv2.Sobel(img,cv2.CV_64F,0,1)
sobelxy = cv2.Sobel(img,cv2.CV_64F,1,1)
laplacian = cv2.Laplacian(img,cv2.CV_64F)#默认ksize=3
plt.subplot(221),plt.imshow(sobelx,'gray')
plt.subplot(222),plt.imshow(sobely,'gray')
plt.subplot(223),plt.imshow(sobelxy,'gray')
plt.subplot(224),plt.imshow(laplacian,'gray')

#人工生成一个高斯核,去和函数生成的比较
kernel = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]],np.float32)#
img1 = np.float64(img)#转化为浮点型的
img_filter = cv2.filter2D(img1,-1,kernel)
sobelxy1 = cv2.Sobel(img1,-1,1,1)
plt.figure()
plt.subplot(121),plt.imshow(img_filter,'gray')
plt.subplot(122),plt.imshow(sobelxy1,'gray')

#canny
edges = cv2.Canny(img,100,200)#其他的默认3,false; 范围[100,200]
plt.subplot(121),plt.imshow(img,'gray')
plt.subplot(122),plt.imshow(edges,'gray')

#高斯金字塔
img1 = cv2.pyrDown(img)
img2 = cv2.pyrUp(img1)
plt.subplot(131),plt.imshow(img,'gray'),plt.title('original')
plt.subplot(132),plt.imshow(img1,'gray'),plt.title('down')
plt.subplot(133),plt.imshow(img2,'gray'),plt.title('up')

#拉普拉斯金字塔 ,由图像的高斯金字塔得到
img1 = cv2.pyrDown(img)#高斯金字塔
temp_img1 = cv2.pyrDown(img1)
temp = cv2.pyrUp(temp_img1)
height,width=img1.shape[:2]
temp=cv2.resize(temp,(width,height),interpolation=cv2.INTER_CUBIC)
img2 = img1 - temp #拉普拉斯金字塔
plt.subplot(131),plt.imshow(img,'gray'),plt.title('original')
plt.subplot(132),plt.imshow(img1,'gray'),plt.title('gas')
plt.subplot(133),plt.imshow(img2,'gray'),plt.title('Laplas')

#灰度直方图的三种方法
#opencv方法读取-cv2.calcHist(速度最快)
#图像,通道[0]-灰度图,掩膜-无,灰度级,像素范围
hist_cv = cv2.calcHist([img],[0],None,[256],[0,256])
#numpy方法读取-np.histogram()
hist_np,bins = np.histogram(img.ravel(),256,[0,256])
#numpy的另一种方法读取-np.bincount()(速度=10倍法2)
hist_np2 = np.bincount(img.ravel(),minlength=256)
plt.subplot(221),plt.imshow(img,'gray')
plt.subplot(222),plt.plot(hist_cv)
plt.subplot(223),plt.plot(hist_np)
plt.subplot(224),plt.plot(hist_np2)

#直方图均衡化:利用图像直方图对对比度进行调整的方法
res = cv2.equalizeHist(img)
#方法二,局部均衡
clahe = cv2.createCLAHE(clipLimit=2,tileGridSize=(10,10))
cl1 = clahe.apply(img)

plt.subplot(131),plt.imshow(img,'gray')
plt.subplot(132),plt.imshow(res,'gray')
plt.subplot(133),plt.imshow(cl1,'gray')

猜你喜欢

转载自blog.csdn.net/lusics/article/details/88215955