参考学习:3h精通Opencv , Opencv官方教程
Picture
Lena.jpg
Test1-调用摄像机or读取视频
import cv2 as cv
import numpy as np
cap = cv.VideoCapture(1)
cap.set(3,640)
cap.set(4,480)
cap.set(10,50)
while True :
success,img = cap.read()
cv.imshow('Video',img)
if cv.waitKey(1) & 0xff == ord('q'):
break
tips:
- cv.VideoCapture(1)
参数为设备号,以笔记本举例,0为自带摄像头,1为外接摄像头,也可导入视频(如MP4) - set(id,value)
其中定义视频多种属性,常用的有
3–视频流的宽度
4–视频流的高度
5–视频帧率
10–视频的亮度(只用于相机)
11–图像的对比度(仅用于相机)
12–图像的饱和度(仅适用于相机)
13–图像的色调Hue (仅适用于相机)
15–曝光(仅适用于相机)
Test2 几种图片处理的函数
import cv2 as cv
import numpy as np
kernel = np.ones((5,5),np.uint8)#核
img =cv.imread('../Figure/lena.jpg')
imgGray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)#灰度化
imgBlur = cv.GaussianBlur(imgGray,(13,13),0)#高斯模糊
imgCanny = cv.Canny(img,200,150)#用于对图像的边缘检测,阈值设置
imgDialation = cv.dilate(img,kernel,iterations=1)#膨胀
imgEroded = cv.erode(img,kernel,iterations=1)#腐蚀
print(imgDialation.shape,img.shape)
cv.imshow("Image",img)
cv.imshow("Blur Image",imgBlur)
cv.imshow("Gray Image",imgGray)
cv.imshow("Canny Image",imgCanny)
cv.imshow("Dilation Image",imgDialation)
cv.imshow("Eroded Image",imgEroded)
cv.waitKey(0)
Test3 调整图片大小和裁剪
import cv2 as cv
import numpy as np
img =cv.imread('../Figure/lena.jpg')
#调整大小
imgResize = cv.resize(img,(1000,1000))
imgCropped = img[0:200,0:200]
cv.imshow("Image",img)
cv.imshow("Resize Image",imgResize)
cv.imshow("Corpped Image",imgCropped)
cv.waitKey(0)
Test4 图片水平/垂直堆叠
import cv2 as cv
import numpy as np
img = cv.imread('../Figure/lena.jpg',1)
imgHor = np.hstack((img,img))#水平堆叠
imgVer = np.vstack((img,img))#垂直堆叠
cv.imshow("imgHorrizional",imgHor)
cv.imshow("imgVer",imgVer)
cv.waitKey(0)
Test5 通过TrackBar来保留图片中对应的颜色
此方法可用来 形状检测和对象定位
import cv2 as cv
import numpy as np
def empty(a):
pass
cv.namedWindow("TrackBars")#创建窗口
cv.resizeWindow("TrackBars",640,480)#重置窗口大小
cv.createTrackbar("Hue Min","TrackBars",0,179,empty)#创建bar:命名,所在窗口,阈值,拖动后的反馈函数
cv.createTrackbar("Hue Max","TrackBars",178,179,empty)
cv.createTrackbar("Sat Min","TrackBars",63,255,empty)
cv.createTrackbar("Sat Max","TrackBars",255,255,empty)
cv.createTrackbar("Val Min","TrackBars",45,255,empty)
cv.createTrackbar("Val Max","TrackBars",255,255,empty)
while 1:
img = cv.imread('../Figure/lanbojini.jpg', 1)
imgHSV = cv.cvtColor(img, cv.COLOR_BGR2HSV)
#色调(H),饱和度(S),明度(V)
#在 HSV 颜色空间下,比 BGR 更容易跟踪某种颜色的物体,常用于分割指定颜色的物体。
h_min = cv.getTrackbarPos("Hue Min", "TrackBars")#获取Bar的值
h_max = cv.getTrackbarPos("Hue Max", "TrackBars")
s_min = cv.getTrackbarPos("Sat Min", "TrackBars")
s_max = cv.getTrackbarPos("Sat Max", "TrackBars")
v_min = cv.getTrackbarPos("Val Min", "TrackBars")
v_max = cv.getTrackbarPos("Val Max", "TrackBars")
lower = np.array([h_min,s_min,v_min])
upper = np.array([h_max,s_max,v_max])
mask = cv.inRange(imgHSV,lower,upper)#根据阈值二值化,可以同时针对多通道进行操作
imgResult = cv.bitwise_and(img,img,mask=mask)#遮罩与原图进行与操作
imgStack = np.hstack([img,imgResult])#水平堆叠显示
cv.imshow("ImageHSV", imgHSV)
cv.imshow("Imagemask", mask)
cv.imshow("ImageStack", imgStack)
cv.waitKey(1)
Test6 通过颜色进行边缘检测
import cv2 as cv
import numpy as np
def getContours(img):
contours,hierarchy = cv.findContours(img,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv.contourArea(cnt)#面积
print(area)
cv.drawContours(imgContour,cnt,-1,(255,0,0),3)
#绘制轮廓:所在图像,轮廓,需要绘制的轮廓的指数,颜色,粗细
peri = cv.arcLength(cnt,True)#周长
approx = cv.approxPolyDP(cnt,0.02*peri,True)
#主要功能是把一个连续光滑曲线折线化,对图像轮廓点进行多边形拟合。
#参数1是源图像的某个轮廓;
#参数2(epsilon)是一个距离值,表示多边形的轮廓接近实际轮廓的程度,值越小,越精确;
#参数3表示是否闭合
objCor = len(approx)
print(objCor)
x,y,w,h = cv.boundingRect(approx)
#用最小的矩阵把轮廓包裹起来,x,y是矩阵左上点的坐标,w,h是矩阵的宽和高
cv.rectangle(imgContour,(x-10,y-10),(x+w+10,y+h+10),(0,0,255),2)
#绘制矩形
#通过判断点数,判断形状
if objCor == 3:objectType = "Tri"
elif objCor ==4:
aspRatio = w/float(h)
if aspRatio>0.95 and aspRatio< 1.05:objectType = 'Square'
else:objectType = 'Rectange'
elif objCor > 4:objectType = "Circles"
else:objectType = "None"
cv.putText(imgContour,objectType,(x+(w//2)-10,y+(h//2)-10),cv.FONT_HERSHEY_COMPLEX,0.7,(0,0,0),2)
#在图片上对应位置写上字符
path = '../Figure/shapes.png'
img = cv.imread(path,1)
imgContour = img.copy()
imgGray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
imgBlur = cv.GaussianBlur(imgGray,(7,7),1)#内核,以及sigma
imgCanny = cv.Canny(imgBlur,100,100)
getContours(imgCanny)
cv.imshow('ImageGray',imgGray)
cv.imshow("ImageBlur",imgBlur)
cv.imshow("ImageCanny",imgCanny)
cv.imshow("ImageContour",imgContour)
cv.waitKey(0)
Test7 人脸检测
这里使用了相关的库文件可至此查找下载GitHub
import cv2 as cv
import numpy as np
faceCascade = cv.CascadeClassifier('Resources/haarcascade_frontalface_default.xml')
path = '../Figure/lena.jpg'
img = cv.imread(path,1)
imgGray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(imgGray,1.1,4)
for (x,y,w,h) in faces:
cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv.imshow("Result",img)
cv.waitKey(0)