系统环境:win7旗舰版、
版本:python3.5.6 、opencv 3.2.0
关于opencv_python库的安装,可浏览之前的博客,此处不再赘述。
1.hello,opencv
import cv2 as cv
img=cv.imread("qie.jpg") #读取图像
cv.imshow("who",img)
cv.waitKey(0)
cv.destroyAllWindows()
运行结果:
2.hello,camera
#打开摄像头
import cv2
import numpy
import matplotlib.pyplot as plot
#摄像头对象
cap=cv2.VideoCapture(0)
#显示
while(1):
ret,frame = cap.read()
cv2.imshow("capture",frame)
if(cv2.waitKey(1) & 0xFF==ord('q')):
break
cap.release()
cv2.destroyAllWindows()
3.保存图片
#保存图片
import cv2
cap = cv2.VideoCapture(0)
i=0
while(1):
ret, frame = cap.read()
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord(' '):
i=i+1
imgName="i_"+str(i)
cv2.imwrite("img/"+imgName+".jpeg", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
4.图像二值化
import cv2 as cv
#灰度模式读取图像
img=cv.imread("img/i1.jpeg",0)
#设置阈值进行二值化
th=100
ret,binary1=cv.threshold(img,th,255,cv.THRESH_BINARY_INV)
ret,binary2=cv.threshold(img,th,255,cv.THRESH_BINARY)
ret,binary3=cv.threshold(img,th,255,cv.THRESH_TRUNC)
ret,binary4=cv.threshold(img,th,255,cv.THRESH_TOZERO)
ret,binary5=cv.threshold(img,th,255,cv.THRESH_TOZERO_INV)
ret,binary6=cv.threshold(img,th,255,cv.THRESH_OTSU)
ret,binary7=cv.threshold(img,th,255,cv.THRESH_TRIANGLE)
cv.imshow("THRESH_BINARY_INV",binary1)
cv.imshow("THRESH_BINARY",binary2)
cv.imshow("THRESH_TRUNC",binary3)
cv.imshow("THRESH_TOZERO",binary4)
cv.imshow("THRESH_TOZERO_INV",binary5)
cv.imshow("THRESH_OTSU",binary6)
cv.imshow("THRESH_TRIANGLE",binary7)
cv.waitKey(0)
cv.destroyAllWindows()
5.显示轮廓边缘
#摄像头并显示轮廓
import cv2
cap = cv2.VideoCapture(0)
i=0
while(1):
ret, frame = cap.read()
img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
img_gb = cv2.GaussianBlur(img_gray, (5, 5), 0)
edges = cv2.Canny(img_gb, 100 , 200)
cv2.imshow("capture", edges)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()