读图,写图,展示图
import cv2
img = cv2.imread("heart.jpg") # 通道顺序(B,G,R)
cv2.imshow("heart", img)
cv2.waitKey(0)
cv2.imwrite("output.jpg", img)
# 若为RGBA图片
img = cv2.imread("test.jpg", -1) # 通道顺序(B,G,R,A)
cv2.imwrite("output.png", img) # 需保存为png格式才能保留alpha通道
# 插曲:检测文件夹是否存在,若不存在则新建一个
if not os.path.exists(outputpath):
os.makedirs(outputpath)
读视频,并显示
cap = cv2.VideoCapture("V03_1.avi")
while cap.isOpened():
ret, frame = cap.read()
cv2.imshow('image', frame)
if cv2.waitKey(33) == ord('q'): # q键退出
break
cap.release()
cv2.destroyAllWindows()
视频切帧
"""将视频读入,然后每一帧存为一张图片"""
inputpath = "./video/IMG_2760.MOV"
outputpath = "./videoframe/"
cap = cv2.VideoCapture(inputpath)
if not os.path.exists(outputpath):
os.makedirs(outputpath)
num = 1
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
filename = "frame" + str(num) + ".jpg"
cv2.imwrite(os.path.join(outputpath, filename), frame)
num += 1
cap.release()
BGR转RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
画线,画框
red = (0, 0, 255)
greem = (0, 255, 0)
cv2.line(img, (20, 20), (100, 100), red) # 在img图像的坐标(20, 20)和(100, 100)之间画一条红线
cv2.line(img, (20, 20), (100, 100), red, 4) # 最后一个参数设置线的粗细
cv2.rectangle(img, (10, 10), (60, 60), green) # 在以img图像(10, 10)和(60, 60)为左上和右下画矩形
截取图片
roi = img[308:540, 38:216]
cv2.imwrite("object.jpg", roi)
分离色彩通道
BGRImg = cv2.imread(ImgPath)
B = BGRImg[:, :, 0]
G = BGRImg[:, :, 1]
R = BGRImg[:, :, 2]
# or
BGRImg = cv2.imread(ImgPath)
B, G, R = cv2.split(BGRImg)
# 注意,cv2.split的速度比直接索引要慢,但cv2.split返回的是拷贝,直接索引返回的是引用(改变B就会改变BGRImg)
画多边形
Pts = np.array([[38, 308], [216, 308], [216, 540], [38, 540]], np.int32)
Pts = Pts.reshape((-1, 1, 2))
cv2.polylines(img, [Pts], True, (0, 255, 255), 3)
图片变换
Resize
object_img = cv2.resize(object_img, target_shape)
旋转
1 使用warAffine函数,优点是可选角度多,缺点是会被截取
(h, w) = object_img.shape[:2]
center = (w/2, h/2)
M = cv2.getRotationMatrix2D(center, 45, 1)
rotated = cv2.warpAffine(object_img, M, (w, h))
cv2.imshow("Rotated by 45 Degrees", rotated)
2 使用rotate函数,优点是图片不会被截取,缺点是只能旋转90°的倍数
rotated = cv2.rotate(img, 0) # 旋转90°
rotated = cv2.rotate(img, 1) # 旋转180°
rotated = cv2.rotate(img, 2) # 旋转270°
仿射变换
rows, cols, ch = img.shape
pts1 = np.float32([[0, 0], [cols - 1, 0], [0, rows - 1]])
pts2 = np.float32([[cols * 0.2, rows * 0.1], [cols * 0.9, rows * 0.2], [cols * 0.1, rows * 0.9]])
M = cv2.getAffineTransform(pts1, pts2)
dst = cv2.warpAffine(img, M, (cols, rows))
opencv进行任意仿射变换的方法是先找三个点,分别给出这三个点进行变换前的坐标与变换后的坐标。
然后是用cv2.getAffineTransform函数进行变换矩阵的计算
再使用cv2.warpAffine函数来进行仿射变换