介紹:強大的視覺處理工具庫
一、 圖片處理
圖片讀取&顯示&存儲
-
cv2.imread(filename, flags=None)讀入圖片,格式為ndarry
flags:讀入類型
cv2.IMREAD_COLOR:默認參數,讀入一副彩色圖片,忽略alpha通道
cv2.IMREAD_GRAYSCALE:讀入灰度圖片
cv2.IMREAD_UNCHANGED:讀入完整圖片,包括alpha通道(png有,jpg無) -
cv2.imshow('wind_name', img)在wind_name窗口中顯示圖片 -
cv2.waitKey()窗口等待任意鍵盤按鍵輸入,0為一直等待,其他數字為毫秒數 -
cv2.destroyAllWindows()銷毀窗口,退出程序 -
cv2.imwrite(filename, img, params=None)將img存入filename中
添加圖形&文本
參考:www.cnblogs.com/mfmdaoyou/p/6745132.html
-
cv2.line(img,Point pt1,Point pt2,color,thickness=1,line_type=8 shift=0)繪制直線
pt1和pt2為線的兩端,顏色color,粗細thickness,shift=-1表示對圖形進行填充 -
cv2.rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)繪制矩形
pt1和pt2為左上角和右下角 -
cv2. circle(img, center, radius, color, thickness=None, lineType=None, shift=None)繪制圓
圓中心center和半徑radius -
cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=None, lineType=None, shift=None)繪制橢圓
橢圓示例圖 -
cv2.polylines(img, pts, isClosed, color, thickness=None, lineType=None, shift=None)繪制多邊形
pts: 多邊形各頂點坐標
isClosed: 多邊形是否閉合 -
cv2.putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None)添加文本
org:左上角坐標
fontFace:字體, 可選cv2.FONT_HERSHEY_SIMPLEX
fontScale, color, thickness:字體大小/顏色/粗細
圖像變換
參考:
https://blog.csdn.net/qq_37541097/article/details/79999902
-
cv2.cvtColor(src, code, dst=None, dstCn=None)顏色空間轉換
code:轉換類型,常用如cv2.COLOR_BGR2RGB,cv2.COLOR_BGR2GRAY,cv2.COLOR_BGR2HSV -
_, mask = cv2.threshold(src, thresh, maxval, type, dst=None)灰度圖二值化
src,thresh,maxval: 灰度圖,閾值,最大值
type:閾值類型,常見的類型有
二值化類型 - 旋轉圖像
M = cv2.getRotationMatrix2D((width/2, height/2), angle, scale)
ratation = cv2.warpAffine(image, M, (width, height))
M為旋轉矩陣,第一個參數是設定旋轉中心,第二個參數是旋轉角度(單位是度,逆時針為正),第三個參數是縮放比例
參考:https://blog.csdn.net/weixin_35732969/article/details/83779660
-
cv2.resize(im, (width, height), interpolation)圖像縮放
(width, height),interpolation:縮放后圖像大小, 插值類型
參考:https://blog.csdn.net/liangjiubujiu/article/details/80437481插值類型
二、 視頻處理
參考:https://blog.csdn.net/qq_37541097/article/details/79999902
import cv2
import numpy as np
cap = cv2.VideoCapture('video.mp4') # 打開視頻文件
if cap.isOpened() is False: # 確認視頻是否成果打開
print('Error')
exit(1)
frame_width = int(cap.get(3)) # 獲取圖片幀寬度
frame_height = int(cap.get(4)) # 獲取圖像幀高度
# 創(chuàng)建保存視頻,指定保存視頻名稱,指定視頻編碼器,視頻幀率,圖像幀尺寸
out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, (frame_width, frame_height))
ret, frame = cap.read() # 讀取一幀圖像,當視頻幀讀取完畢ret標識符為False
while ret:
cv2.imshow('frame', frame) # 顯示圖像幀
cv2.waitKey(20) # 幀間隔為20ms
frame = cv2.flip(frame, 0) # 對圖像進行水平翻轉
out.write(frame) # 將frame寫入視頻
ret, frame = cap.read() # 讀取下一幀
cap.release()
out.release()


