目录
- 图像基本操作
- 数据读取——图像
- 数据读取——视频
- 截取部分图像数据 ROI——Region of Interest
- 颜色通道提取
- 边界填充
- 数值计算
- 图像融合
- 图像处理
- 灰度图
- HSV
- 图像阈值
- 图像平滑(滤波)
- 形态学-腐蚀操作
- 形态学-膨胀操作
- 开运算与闭运算
- 梯度运算
- 礼帽与黑帽
- 图像梯度——Sobel算子
- 看看Lena
- 图像梯度-Scharr算子
- 图像梯度-laplacian算子
- Canny边缘检测
- 1:高斯滤波器
- 2:梯度和方向
- 3:非极大值抑制
- 4:双阈值检测(确定最终边缘)
- 图像金字塔
- 图像轮廓
- 绘制轮廓
- 轮廓特征
- 轮廓近似
- 边界矩形
- 外接圆
图像基本操作
数据读取——图像
注意:opencv默认读取格式是bgr而不是rgb,与matplotlib有一些冲突
import cv2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inlineimg=cv2.imread('./汪学长的随堂资料/4/图像操作/cat.jpg')
img
#图像的显示,也可以创建多个窗口
cv2.imshow('image',img)
# 等待时间,毫秒级,0表示任意键终止
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1) # MacOS 如果出现内核卡住,写上这样代码;Windows可不用写这行代码
"""
在调用cv2.destroyAllWindows()关闭窗口后使用cv2.waitKey(1)的常见原因是,有时cv2.destroyAllWindows()可能不会立即关闭窗口,
而cv2.waitKey(1)会给它时间来处理窗口关闭的事件。这种情况下cv2.waitKey(1)不是用于检测键盘输入,而是用于提供时间来处理窗口事件。
"""
def cv_show(name,img):cv2.imshow(name,img) cv2.waitKey(0)cv2.destroyAllWindows()
img.shape
(414, 500, 3)
img=cv2.imread('cat.jpg',cv2.IMREAD_GRAYSCALE)
img
img=cv2.imread('./汪学长的随堂资料/4/图像操作/cat.jpg',cv2.IMREAD_GRAYSCALE)
img
img.shape
(414, 500)
#图像的显示,也可以创建多个窗口
cv2.imshow('image',img)
# 等待时间,毫秒级,0表示任意键终止
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
#保存
cv2.imwrite('mycat.png',img)
数据读取——视频
vc = cv2.VideoCapture('./汪学长的随堂资料/4/图像操作/test.mp4')
# 检查是否打开正确
if vc.isOpened(): open, frame = vc.read()
else:open = False
while open:ret, frame = vc.read()if frame is None:breakif ret == True:gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)cv2.imshow('result', gray)if cv2.waitKey(100) & 0xFF == 27:breakvc.release()
cv2.destroyAllWindows()
cv2.waitKey(1) # MacOS 如果出现内核卡住,写上这样代码;Windows可不用写这行代码
截取部分图像数据 ROI——Region of Interest
img=cv2.imread('./汪学长的随堂资料/4/图像操作/cat.jpg') # ndarray
cat=img[0:50,0:200]
cv_show('cat',cat)
颜色通道提取
b,g,r=cv2.split(img)
g
img=cv2.merge((b,g,r))
img.shape
(414, 500, 3)
# 只保留R
cur_img = img.copy()
cur_img[:,:,0] = 0
cur_img[:,:,1] = 0
cv_show('R',cur_img)
# 只保留G
cur_img = img.copy()
cur_img[:,:,0] = 0
cur_img[:,:,2] = 0
cv_show('G',cur_img)
# 只保留B
cur_img = img.copy()
cur_img[:,:,1] = 0
cur_img[:,:,2] = 0
cv_show('B',cur_img)
边界填充
top_size,bottom_size,left_size,right_size = (50,50,50,50)replicate = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_WRAP)
constant = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,cv2.BORDER_CONSTANT, value=0)
import matplotlib.pyplot as plt
plt.subplot(231), plt.imshow(img, 'gray'), plt.title('ORIGINAL')
plt.subplot(232), plt.imshow(replicate, 'gray'), plt.title('REPLICATE')
plt.subplot(233), plt.imshow(reflect, 'gray'), plt.title('REFLECT')
plt.subplot(234), plt.imshow(reflect101, 'gray'), plt.title('REFLECT_101')
plt.subplot(235), plt.imshow(wrap, 'gray'), plt.title('WRAP')
plt.subplot(236), plt.imshow(constant, 'gray'), plt.title('CONSTANT')plt.show()
数值计算
img_cat=cv2.imread('./汪学长的随堂资料/4/图像操作/cat.jpg')
img_dog=cv2.imread('./汪学长的随堂资料/4/图像操作/dog.jpg')
img_cat2= img_cat +10
img_cat[:5,:,0]
img_cat2[:5,:,0]
#相当于% 256
(img_cat + img_cat2)[:5,:,0] # 142+152=294
cv2.add(img_cat,img_cat2)[:5,:,0]
图像融合
img_cat + img_dog
img_cat.shape
(414, 500, 3)
img_dog = cv2.resize(img_dog, (500, 414))
img_dog.shape
(414, 500, 3)
res = cv2.addWeighted(img_cat, 0.4, img_dog, 0.6, 0)
plt.imshow(res)
res = cv2.resize(img, (0, 0), fx=3, fy=1)
plt.imshow(res)
res = cv2.resize(img, (0, 0), fx=1, fy=3)
plt.imshow(res)
图像处理
灰度图
import cv2 #opencv读取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt#Matplotlib是RGB
%matplotlib inline img=cv2.imread('./汪学长的随堂资料/4/图像操作/cat.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img_gray.shape
import warnings
warnings.filterwarnings('ignore')
cv2.imshow("img_gray", img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
HSV
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)cv2.imshow("hsv", hsv)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
图像阈值
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)titles = ['Original Image', '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('./汪学长的随堂资料/4/图像操作/lenaNoise.png')cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 均值滤波
# 简单的平均卷积操作
blur = cv2.blur(img, (3, 3))cv2.imshow('blur', blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 方框滤波
# 基本和均值一样,可以选择归一化
box = cv2.boxFilter(img,-1,(3,3), normalize=True) cv2.imshow('box', box)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 方框滤波
# 基本和均值一样,可以选择归一化,容易越界
box = cv2.boxFilter(img,-1,(3,3), normalize=False) cv2.imshow('box', box)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 高斯滤波
# 高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的
aussian = cv2.GaussianBlur(img, (5, 5), 1) cv2.imshow('aussian', aussian)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 中值滤波
# 相当于用中值代替
median = cv2.medianBlur(img, 5) # 中值滤波cv2.imshow('median', median)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 展示所有的
res = np.hstack((blur,aussian,median))
#print (res)
cv2.imshow('median vs average', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
形态学-腐蚀操作
import cv2 #opencv读取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt#Matplotlib是RGB
import warnings
warnings.filterwarnings('ignore')img = cv2.imread('./汪学长的随堂资料/4/图像操作/dige.png')cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 1)cv2.imshow('erosion', erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
pie = cv2.imread('./汪学长的随堂资料/4/图像操作/pie.png')cv2.imshow('pie', pie)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
kernel = np.ones((30,30),np.uint8)
erosion_1 = cv2.erode(pie,kernel,iterations = 1)
erosion_2 = cv2.erode(pie,kernel,iterations = 2)
erosion_3 = cv2.erode(pie,kernel,iterations = 3)
res = np.hstack((erosion_1,erosion_2,erosion_3))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
形态学-膨胀操作
img = cv2.imread('./汪学长的随堂资料/4/图像操作/dige.png')
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
kernel = np.ones((3,3),np.uint8)
dige_erosion = cv2.erode(img,kernel,iterations = 1)cv2.imshow('erosion', erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
kernel = np.ones((3,3),np.uint8)
dige_dilate = cv2.dilate(dige_erosion,kernel,iterations = 1)cv2.imshow('dilate', dige_dilate)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
pie = cv2.imread('./汪学长的随堂资料/4/图像操作/pie.png')kernel = np.ones((30,30),np.uint8)
dilate_1 = cv2.dilate(pie,kernel,iterations = 1)
dilate_2 = cv2.dilate(pie,kernel,iterations = 2)
dilate_3 = cv2.dilate(pie,kernel,iterations = 3)
res = np.hstack((dilate_1,dilate_2,dilate_3))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
开运算与闭运算
# 开:先腐蚀,再膨胀
img = cv2.imread('./汪学长的随堂资料/4/图像操作/dige.png')kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)cv2.imshow('opening', opening)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 闭:先膨胀,再腐蚀
img = cv2.imread('./汪学长的随堂资料/4/图像操作/dige.png')kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)cv2.imshow('closing', closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
梯度运算
# 梯度=膨胀-腐蚀
pie = cv2.imread('./汪学长的随堂资料/4/图像操作/pie.png')
kernel = np.ones((7,7),np.uint8)
dilate = cv2.dilate(pie,kernel,iterations = 5)
erosion = cv2.erode(pie,kernel,iterations = 5)res = np.hstack((dilate,erosion))cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel)cv2.imshow('gradient', gradient)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
礼帽与黑帽
#礼帽
img = cv2.imread('./汪学长的随堂资料/4/图像操作/dige.png')
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
cv2.imshow('tophat', tophat)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
#黑帽
img = cv2.imread('./汪学长的随堂资料/4/图像操作/dige.png')
blackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)
cv2.imshow('blackhat ', blackhat )
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
图像梯度——Sobel算子
import matplotlib.pyplot as plt
import numpy as np# 定义1D图像像素值
pixel_values = [50, 50, 50, 200, 200, 200] #[0, 0, 150, 0, 0]# 创建对应的x坐标
x = np.arange(len(pixel_values))# 创建图像
plt.figure(figsize=(8, 4))
plt.stem(x, pixel_values, use_line_collection=True)
plt.title('1D Image')
plt.xlabel('Pixel Position')
plt.ylabel('Pixel Intensity')# 显示图像
plt.show()
右减左,上减下
import cv2
img = cv2.imread('./汪学长的随堂资料/4/图像操作/pie.png',cv2.IMREAD_GRAYSCALE)
cv2.imshow("img",img)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.waitKey(1)
def cv_show(img,name):cv2.imshow(name,img)cv2.waitKey()cv2.destroyAllWindows()cv2.waitKey(1)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)cv_show(sobelx,'sobelx')
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
cv_show(sobelx,'sobelx')
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
cv_show(sobely,'sobely')
见下
sobelxy=cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3)
sobelxy = cv2.convertScaleAbs(sobelxy)
cv_show(sobelxy,'sobelxy')
看看Lena
img = cv2.imread('./汪学长的随堂资料/4/图像操作/lena.jpg', cv2.IMREAD_GRAYSCALE)
cv_show(img,'img')
img = cv2.imread('./汪学长的随堂资料/4/图像操作/lena.jpg',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
cv_show(sobelxy,'sobelxy')
img = cv2.imread('./汪学长的随堂资料/4/图像操作/lena.jpg',cv2.IMREAD_GRAYSCALE)sobelxy=cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3)
sobelxy = cv2.convertScaleAbs(sobelxy)
cv_show(sobelxy,'sobelxy')
图像梯度-Scharr算子
权重更大一些
图像梯度-laplacian算子
相当于使用的是二阶导,也就是一阶导的变化率,对变化更加敏感,但是同时对噪音点也更敏感
import numpy as np
import cv2
def cv_show(img,name):cv2.imshow(name,img)cv2.waitKey()cv2.destroyAllWindows()cv2.waitKey(1)#不同算子的差异
img = cv2.imread('./汪学长的随堂资料/4/图像操作/lena.jpg',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0) scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(scharrx,0.5,scharry,0.5,0) laplacian = cv2.Laplacian(img,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian) color_img = cv2.imread('./汪学长的随堂资料/4/图像操作/lena.jpg')res = np.hstack((img, sobelxy,scharrxy,laplacian))
cv_show(res,'res')
Canny边缘检测
1:高斯滤波器
2:梯度和方向
3:非极大值抑制
4:双阈值检测(确定最终边缘)
img=cv2.imread("./汪学长的随堂资料/4/图像操作/lena.jpg",cv2.IMREAD_GRAYSCALE)v1=cv2.Canny(img,80,150)
v2=cv2.Canny(img,50,100)res = np.hstack((v1,v2))
cv_show(res,'res')
img=cv2.imread("./汪学长的随堂资料/4/图像操作/car.png",cv2.IMREAD_GRAYSCALE)v1=cv2.Canny(img,120,250)
v2=cv2.Canny(img,50,100)res = np.hstack((v1,v2))
cv_show(res,'res')
图像金字塔
link
img=cv2.imread("./汪学长的随堂资料/4/图像操作/AM.png")
cv_show(img,'img')
print(img.shape)
(442, 340, 3)
up=cv2.pyrUp(img)
cv_show(up,'up')
print(up.shape)
(884, 680, 3)
down=cv2.pyrDown(img)
cv_show(down,'down')
print(down.shape)
(221, 170, 3)
up2=cv2.pyrUp(up)
cv_show(up2,'up2')
print (up2.shape)
(1768, 1360, 3)
up=cv2.pyrUp(img)
up_down=cv2.pyrDown(up)
cv_show(up_down,'up_down')
cv_show(np.hstack((img,up_down)),'up_down')
down=cv2.pyrDown(img)
down_up=cv2.pyrUp(down)
l_1=img-down_up
cv_show(l_1,'l_1')
图像轮廓
img = cv2.imread('./汪学长的随堂资料/4/图像操作/contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv_show(thresh,'thresh')
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
绘制轮廓
#传入绘制图像,轮廓,轮廓索引,颜色模式,线条厚度
# 注意需要copy,要不原图会变。。。
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2)
cv_show(res,'res')
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, 2, (0, 0, 255), 2)
cv_show(res,'res')
轮廓特征
cnt = contours[0]
#面积
cv2.contourArea(cnt)
8500.5
#周长,True表示闭合的
cv2.arcLength(cnt,True)
437.9482651948929
轮廓近似
img = cv2.imread('./汪学长的随堂资料/4/图像操作/contours2.png')gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]draw_img = img.copy()
res = cv2.drawContours(draw_img, [cnt], -1, (0, 0, 255), 2)
cv_show(res,'res')
epsilon = 0.15*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)draw_img = img.copy()
res = cv2.drawContours(draw_img, [approx], -1, (0, 0, 255), 2)
cv_show(res,'res')
边界矩形
img = cv2.imread('./汪学长的随堂资料/4/图像操作/contours.png')gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]x,y,w,h = cv2.boundingRect(cnt)
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv_show(img,'img')
area = cv2.contourArea(cnt)
x, y, w, h = cv2.boundingRect(cnt)
rect_area = w * h
extent = float(area) / rect_area
print ('轮廓面积与边界矩形比',extent)
轮廓面积与边界矩形比 0.5154317244724715
外接圆
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img,center,radius,(0,255,0),2)
cv_show(img,'img')