1. 读取显示保存的方法
import cv2
# show and save the picture
img = cv2.imread('opencv.jpg',0)
cv2.imshow('image',img)
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('{}'.format('opencv.png'),img)
选择分支
import cv2
# show and save the picture
img = cv2.imread('opencv.jpg',0)
cv2.imshow('image',img)
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
k=cv2.waitKey(0)
if k==27:
cv2.destroyAllWindows()
elif k==ord('s'):
cv2.imwrite('{}'.format('opencv.png'),img)
cv2.destroyAllWindows()
2. 摄像头读取视频
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret,frame=cap.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1)&0xFF==ord('q'):
break
cap.release()
cv2.destroyAllWindows()
获取保存播放视频
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))
while(cap.isOpened()):
ret,frame = cap.read()
if ret == True:
frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1)&0xFF==ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
3. 画曲线,圆,椭圆
import cv2
import numpy as np
img = np.zeros((512,512,3), np.uint8)
cv2.line(img,(0,0),(511,511),(255,0,0),5)
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv2.circle(img,(447,63),63,(0,0,255),-1)
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
pts = np.array([[10,5],[20,30],[70,20],[50,10]],np.int32)
pts = pts.reshape((-1,1,2))
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'drawing',(10,500),font,4,(255,255,255),2)
cv2.namedWindow('drawing',cv2.WINDOW_NORMAL)
cv2.imshow('drawing',img)
cv2.waitKey(0)
cv2.destroyAllWindows('drawing')
4. 颜色变换器
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((300,512,3),np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
switch='0:OFF\n1:ON'
cv2.createTrackbar(switch,'image',0,1,nothing)
while(1):
cv2.imshow('image',img)
k=cv2.waitKey(1)&0xFF
if k == 27:
break
r = cv2.getTrackbarPos('R','image')
g = cv2.getTrackbarPos('G','image')
b = cv2.getTrackbarPos('B','image')
s = cv2.getTrackbarPos(switch,'image')
if s==0:
img[:]=0
else:
img[:]=[b,g,r]
cv2.destroyAllWindows()
5. 画板画图
import cv2
import numpy as np
def nothing(x):
pass
drawing=False
mode=True
ix,iy=-1,-1
def draw_circle(event,x,y,flags,param):
r=cv2.getTrackbarPos('R','image')
g=cv2.getTrackbarPos('G','image')
b=cv2.getTrackbarPos('B','image')
color=(b,g,r)
global ix,iy,drawing,mode
if event==cv2.EVENT_LBUTTONDOWN:
drawing=True
ix,iy=x,y
elif event==cv2.EVENT_MOUSEMOVE and flags==cv2.EVENT_FLAG_LBUTTON:
if drawing==True:
if mode==True:
cv2.rectangle(img,(ix,iy),(x,y),color,-1)
else:
cv2.circle(img,(x,y),3,color,-1)
elif event==cv2.EVENT_LBUTTONUP:
drawing=False
if mode==True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
k=cv2.waitKey(1)&0xFF
if k==ord('m'):
mode=not mode
elif k==27:
break
6. opencv知识点
import cv2
import numpy as np
img=cv2.imread('opencv.jpg')
b,g,r=cv2.split(img)
img=cv2.merge(b,g,r) #有问题
px=img[100,100]
px=[255.255,255]
print(px)
blue=img[100,100,0]
print(blue)
print(img.item(10,10,2))
img.itemset((10,10,2),100)
print(img.item(10,10,2))
print(img.shape)
print(img.size)
print(img.dtype)
ball = img[300:340,330:390]
img[273:333,100:160]=ball
while(1):
cv2.imshow('image',img)
k=cv2.waitKey(1)&0xFF
if k==ord('m'):
mode=not mode
elif k==27:
break
7. 镜像
import cv2
import numpy as np
import matplotlib.pyplot as mp
BLUE=[255,0,0]
img1=cv2.imread('test0.jpg')
replicate =cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
reflect =cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
reflect101 =cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
wrap =cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
constant =cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)
mp.subplot(231),mp.imshow(img1,'gray'),mp.title('original')
mp.subplot(232),mp.imshow(img1,'gray'),mp.title('original2')
mp.subplot(233),mp.imshow(img1,'gray'),mp.title('original3')
mp.subplot(234),mp.imshow(img1,'gray'),mp.title('original4')
mp.subplot(235),mp.imshow(img1,'gray'),mp.title('original5')
mp.subplot(236),mp.imshow(img1,'gray'),mp.title('original6')
mp.show()
8. 图片相加,mixup
import cv2
import numpy as np
img1 =cv2.imread('test0.jpg')
img2 =cv2.imread('test0.jpg')
x=cv2.add(img1,img2)
dst = cv2.addWeighted(img1,0.7,img2,0.3,0)
cv2.imshow('dst',x)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
9. 提取颜色追踪
import cv2
import numpy as np
# flags = [i for i in dir(cv2) if i stratswith('COLOR_')]
# print flags
cap = cv2.VideoCapture(0)
while(1):
ret,frame=cap.read()
hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
lower_blue=np.array([110,50,50])
upper_blue=np.array([130,250,250])
mask=cv2.inRange(hsv,lower_blue,upper_blue)
res=cv2.bitwise_and(frame,frame,mask=mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
k=cv2.waitKey(5)&0xFF
if k==27:
break
cv2.destroyAllWindows()
10. 缩放,平移,旋转.仿射变换,透视变换
import numpy as np
import cv2
img=cv2.imread('test.jpg')
# res=cv2.resize(img,None,fx=2,fy=2,interpolation=cv2.INTER_CUBIC)
height,width=img.shape[:2]
res=cv2.resize(img,(2*width,2*width),interpolation=cv2.INTER_CUBIC)
print('i love opencv')
while(1):
cv2.imshow('res',res)
cv2.imshow('img',img)
if cv2.waitKey(1)&0xFF==27:
break
cv2.destroyAllWindows()
11. 图像阈值化
import cv2
import numpy as np
import matplotlib.pyplot as mp
img=cv2.imread('opencv.jpg',0)
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 = ['original Image', 'binary','BINARY_INV', 'TRUNC','TOZERO','tozero_inv']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
mp.subplot(2,3,i+1),mp.imshow(images[i],'gray')
mp.title(titles[i])
mp.xticks([]),mp.yticks([])
mp.show()
12. 模拟虚化
import cv2
import numpy as np
import matplotlib.pyplot as mp
img=cv2.imread('opencv.jpg',0)
img =cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
th3=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
titles=['Original Image','Global Thresholding','adative_mean','adativa_gaussian']
images=[img,th1,th2,th3]
for i in range(4):
mp.subplot(2,2,i+1),mp.imshow(images[i],'gray')
mp.title(titles[i])
mp.xticks([]),mp.yticks([])
mp.show()
13. 二值化
import cv2
import numpy as np
import matplotlib.pyplot as mp
img=cv2.imread('opencv.jpg',0)
ret1,th1=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret2,th2=cv2.threshold(img,127,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
blur=cv2.GaussianBlur(img,(5,5),0)
ret3,th3=cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
image=[img,0,th1,
img,0,th2,
blur,0,th3]
titles=[1,2,3,4,5,6,7,8,9]
for i in range(3):
mp.subplot(3,3,i*3+1),mp.imshow(image[i*3],'gray')
mp.title(titles[i*3]),mp.xticks([]),mp.yticks([])
mp.subplot(3,3,i*3+2),mp.hist(image[i*3].ravel(),256)
mp.title(titles[i*3+1]),mp.xticks([]),mp.yticks([])
mp.subplot(3,3,i*3+3),mp.imshow(image[i*3+2],'gray')
mp.title(titles[i*3+2]),mp.xticks([]),mp.yticks([])
mp.show()
14. 平均滤波器
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as mp
img = cv2.imread('opencv.jpg')
kernel = np.ones((5,5),np.float32)/25
dst=cv2.filter2D(img,-1,kernel)
mp.subplot(121),mp.imshow(img),mp.title('original')
mp.xticks([]),mp.yticks([])
mp.subplot(122),mp.imshow(dst),mp.title('aver')
mp.xticks([]),mp.yticks([])
mp.show()
15. 均值滤波,高斯滤波,双边滤波
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as mp
img = cv2.imread('opencv.jpg')
blur = cv2.blur(img,(50,50))
gaussian_blur = cv2.GaussianBlur(img,(5,5),0)
median =cv2.medianBlur(img,5)
biblur=cv2.bilateralFilter(img,9,75,75)
mp.subplot(231),mp.imshow(img),mp.title('original')
mp.xticks([]),mp.yticks([])
mp.subplot(232),mp.imshow(blur),mp.title('aver')
mp.xticks([]),mp.yticks([])
mp.subplot(233),mp.imshow(gaussian_blur),mp.title('aver')
mp.xticks([]),mp.yticks([])
mp.subplot(234),mp.imshow(blur),mp.title('aver')
mp.xticks([]),mp.yticks([])
mp.subplot(235),mp.imshow(blur),mp.title('aver')
mp.xticks([]),mp.yticks([])
mp.show()
16. 腐蚀膨胀
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as mp
img = cv2.imread('opencv.jpg',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(img,kernel,iterations=1)
dilation=cv2.dilate(img,kernel,iterations=1)
openings=cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
closings=cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
sgd=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
top=cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
black=cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
blur = cv2.blur(img,(50,50))
gaussian_blur = cv2.GaussianBlur(img,(5,5),0)
pic_list=['erosion','dilation','openings','closings','sgd','top','black','blur','gaussian_blur']
for i in range(9):
mp.subplot(3,3,i+1)
mp.imshow(top)
mp.title(pic_list[i],fontsize=8)
mp.xticks([]),mp.yticks([])
mp.show()
17. 拖动鼠标画矩形与圆形
# -*- coding: utf-8 -*-
import cv2
import numpy as np
drawing = False
mode = True
ix,iy = -1,-1
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event==cv2.EVENT_FLAG_LBUTTON:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
if drawing==True:
if mode==True:
cv2.rectangle(img,(ix,iy),(x,y),(0,250,0), -1)
else:
cv2.circle(img,(x,y),3,(0,255,0),-1)
elif event == cv2.EVENT_FLAG_LBUTTON:
drawing==False
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('opencv')
cv2.setMouseCallback('opencv',draw_circle)
while(1):
cv2.imshow('opencv',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
elif cv2.waitKey(1) &0xFF == ord('m'):
mode = not mode
cv2.imwrite('./1.jpg',img)
cv2.destroyAllWindows()
18. 用滑动条做调色板
# -*- coding:utf-8 -*-
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((350, 512, 3), np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('R', 'image', 0,255,nothing)
cv2.createTrackbar('G', 'image', 0,255,nothing)
cv2.createTrackbar('B', 'image', 0,255,nothing)
switch = '0:OFF\n1:ON'
cv2.createTrackbar(switch,'image',0,1,nothing)
while(1):
cv2.imshow('image', img)
k = cv2.waitKey(1)&0xFF
if k==27:
break
r = cv2.getTrackbarPos('R','image')
g = cv2.getTrackbarPos('G','image')
b = cv2.getTrackbarPos('B', 'image')
s = cv2.getTrackbarPos(switch, 'image')
if s==0:
img[:]=0
else:
img[:]=[b,g,r]
cv2.destroyAllWindows()
19. 选取颜色画图形
# -*- coding: utf-8 -*-
import cv2
import numpy as np
def nothing(x):
pass
drawing = False
mode = True
ix,iy = -1,-1
def draw_circle(event,x,y,flags,param):
r = cv2.getTrackbarPos('R','image')
g = cv2.getTrackbarPos('G','image')
b = cv2.getTrackbarPos('B', 'image')
color = (b, g, r)
global ix,iy,drawing,mode
if event==cv2.EVENT_LBUTTON:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
if drawing==True:
if mode==True:
cv2.rectangle(img,(ix,iy),(x,y),(0,250,0), -1)
else:
cv2.circle(img,(x,y),3,(0,255,0),-1)
elif event == cv2.EVENT_LBUTTON:
drawing==False
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1)&0xFF
if k == ord('m'):
mode = not mode
elif k==27:
break