图像入门
python
import numpy as np
import cv2 as cv
# 用灰度模式加载图像
img = cv.imread('C:/Users/HP/Downloads/basketball.png', 0)
# 即使图像路径错误,它也不会抛出任何错误,但是打印 img会给你None
python
cv.imshow('image', img)
cv.waitKey(5000) # 一个键盘绑定函数,它的参数是以毫秒为单位的时间。该函数为任意键盘事件等待指定毫秒。如果你在这段时间内按下任意键,程序将继续。如果传的是 0,它会一直等待键盘按下。
cv.destroyAllWindows()
python
cv.imshow('image', img)
cv.waitKey(5000) # 一个键盘绑定函数,它的参数是以毫秒为单位的时间。该函数为任意键盘事件等待指定毫秒。如果你在这段时间内按下任意键,程序将继续。如果传的是 0,它会一直等待键盘按下。
cv.destroyAllWindows()
python
cv.namedWindow('image', cv.WINDOW_NORMAL) # cv.WINDOW_NORMAL:先创建窗口再加载图片,此时窗口大小可调整
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
python
cv.imwrite('C:/Users/HP/Downloads/basketball_resave.png',img) # 保存
python
# 使用 Matplotlib 来显示图像
from matplotlib import pyplot as plt
img = cv.imread('C:/Users/HP/Downloads/basketball.png',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # 隐藏 X 和 Y 轴的刻度值
plt.show()
视频入门
python
import numpy as np
import cv2 as cv
# 从相机捕捉视频
cap = cv.VideoCapture(0) # 第一个摄像机,第二个为 1
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
# 当所有事完成,释放 VideoCapture 对象
cap.release()
cv.destroyAllWindows()
python
import numpy as np
import cv2 as cv
# 播放视频文件(但是播几秒就会报错是为啥?
cap = 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()
python
import numpy as np
import cv2 as cv
# 存储视频
cap = cv.VideoCapture(0)
# 声明编码器和创建 VideoWrite 对象
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'):
break
else:
break
# 释放已经完成的工作
cap.release()
out.release()
cv.destroyAllWindows()
绘图功能
python
import numpy as np
import cv2 as cv
# 创建一张空白的画布
canvas = np.zeros((512, 512, 3), dtype=np.uint8)
#img = np.zeros((512,512,3), np.uint8)
# 画一条 5px 宽的蓝色对角线
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) # canvas, (center), (axes), angle, start_angle, end_angle, color, thickness
# 用各个顶点组成多边形
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) # canvas, text, position, font, font_scale, color, thickness
cv.imshow('logo',canvas) # 图像的名字,画布代号
cv.waitKey(0)
cv.destroyAllWindows()