图像入门
import numpy as np
import cv2 as cv
img = cv.imread('C:/Users/HP/Downloads/basketball.png', 0)
cv.imshow('image', img)
cv.waitKey(5000)
cv.destroyAllWindows()
cv.imshow('image', img)
cv.waitKey(5000)
cv.destroyAllWindows()
cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
cv.imwrite('C:/Users/HP/Downloads/basketball_resave.png',img)
from matplotlib import pyplot as pltimg = cv.imread('C:/Users/HP/Downloads/basketball.png',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()
视频入门
import numpy as np
import cv2 as cvcap = cv.VideoCapture(0)
while(True):ret, frame = cap.read()gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)cv.imshow('frame',gray)if cv.waitKey(1) & 0xFF == ord('q'):break
cap.release()
cv.destroyAllWindows()
import numpy as np
import cv2 as cvcap = cv.VideoCapture('C:/Users/HP/Downloads/dancing.mp4')
while(cap.isOpened()):ret, frame = cap.read()gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)cv.imshow('frame',gray)if cv.waitKey(1) & 0xFF == ord('q'):break
cap.release()
cv.destroyAllWindows()
import numpy as np
import cv2 as cvcap = cv.VideoCapture(0)
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('C:/Users/HP/Downloads/output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()): ret, frame = cap.read()if ret==True:frame = cv.flip(frame,0)out.write(frame)cv.imshow('frame',frame)if cv.waitKey(1) & 0xFF == ord('q'):breakelse:break
cap.release()
out.release()
cv.destroyAllWindows()
绘图功能
import numpy as np
import cv2 as cv
canvas = np.zeros((512, 512, 3), dtype=np.uint8)
cv.line(canvas,(0,0),(511,511),(255,0,0),5)
cv.rectangle(canvas,(384,0),(510,128),(0,255,0),3)
cv.circle(canvas,(447,63), 63, (0,0,255), -1)
cv.ellipse(canvas,(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))
cv.polylines(canvas,[pts],True,(0,255,255))
cv.putText(canvas, 'OpenCV', (15, 480), cv.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 2) cv.imshow('logo',canvas)
cv.waitKey(0)
cv.destroyAllWindows()