基于python的Opencv项目实战 (一)图像基本操作
程序员文章站
2023-12-23 17:23:51
...
1.图像读取:
-
cv2.IMREAD_COLOR 读取彩图
-
cv2.IMREAD_GRAYSCALE 读取灰度图
import cv2 #opencv默认读取格式是BGR
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread('01.jpg')
print(img) #打出的是三位维数组HWC(高、宽、通道),C是0、1、2,对应3个通道B、G、R
显示:
import cv2 #opencv默认读取格式是BGR
img = cv2.imread('01.jpg', cv2.IMREAD_GRAYSCALE)
print(img.shape)
cv2.imshow('image', img)
cv2.waitKey(0) #停顿时间,单位毫秒,0表示任意键结束
cv2.destroyAllWindows()
保存:
import cv2 #opencv默认读取格式是BGR
img = cv2.imread('01.jpg')
cv2.imwrite('03.png', img) #保存
截取部分图像:
import cv2 #opencv默认读取格式是BGR
img = cv2.imread('01.jpg')
cat = img[0:200, 0:400] #H、W
cv2.imshow('cat', cat)
cv2.waitKey(0)
cv2.destroyAllWindows()
颜色通道提取:
import cv2 #opencv默认读取格式是BGR
img = cv2.imread('01.jpg')
b, g, r = cv2.split(img)
print(b.shape) #各通道是二维
img = cv2.merge((b, g, r))
print(img.shape)
#只保留R
img_tep = img.copy() #以防直接改动img
img_tep[:, :, 0] = 0 #B通道像素置0
img_tep[:, :, 1] = 0 #G通道像素置0
cv2.imshow('R', img_tep)
#只保留G
img_tep0 = img.copy()
img_tep0[:, :, 0] = 0
img_tep0[:, :, 2] = 0
cv2.imshow('G', img_tep0)
#只保留B
img_tep1 = img.copy()
img_tep1[:, :, 1] = 0
img_tep1[:, :, 2] = 0
cv2.imshow('B', img_tep1)
cv2.waitKey(0)
cv2.destroyAllWindows()
边界填充:
import cv2 #opencv默认读取格式是BGR
import matplotlib.pyplot as plt
img = cv2.imread('01.jpg')
top_size, bottom_size, left_size, right_size = 50, 50, 50, 50
replicate = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT101)
wrap = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_WRAP)
constant = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_CONSTANT, value=0)
plt.subplot(2, 3, 1), plt.imshow(img, 'gray'), plt.title('ORIGINAL')
plt.subplot(2, 3, 2), plt.imshow(replicate, 'gray'), plt.title('REPLICATE')
plt.subplot(2, 3, 3), plt.imshow(reflect, 'gray'), plt.title('REFLECT')
plt.subplot(2, 3, 4), plt.imshow(reflect101, 'gray'), plt.title('REFLECT101')
plt.subplot(2, 3, 5), plt.imshow(wrap, 'gray'), plt.title('WRAP')
plt.subplot(2, 3, 6), plt.imshow(constant, 'gray'), plt.title('CONSTANT')
plt.show()
2. 数据读取-视频
-
cv2.VideoCapture 可以捕获摄像头,用数字来控制不同的设备,如0、1
- 若是视频文件,则直接指定文件路径即可
import cv2 #opencv默认读取格式是BGR
vc = cv2.VideoCapture('01.mp4')
if vc.isOpened(): #检查是否打开正确
while 1:
ret, frame = vc.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('result', gray)
# waitKey()取10,代表每10ms走一帧;0xFF取值27,代表按esc退出
if cv2.waitKey(10) & 0xFF == 27:
break
vc.release()
cv2.destroyAllWindows()