環境:
Python版本:3.6.2
opencv版本:opencv-python==3.4.3.18
安裝opencv
pip install opencv-python
對圖片操作
import cv2
# 識別圖片
img = cv2.imread('cup.jpg', flags=cv2.IMREAD_LOAD_GDAL)
# 添加對圖片的處理內容
# 展示的圖片
cv2.imshow('hello', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
其中,flags可以設置爲哪些參數:
IMREAD_UNCHANGED:載入源圖像,並添加alpha通道. (常用)
IMREAD_GRAYSCALE:始終將圖像轉換爲灰度圖再返回(常用選項)
IMREAD_COLOR:總是轉換圖像爲3通道(BGR注意順序)的彩×××像(常用選項)
IMREAD_ANYDEPTH:如果設置了這個,且載入的圖像深度爲16位/32位,那麼就返回相應深度的圖像,否則, 轉換爲8位返回(常用)
IMREAD_ANYCOLOR:如果設置了,那麼就載入任意可能的顏色格式而不進行轉換. (常用)
IMREAD_LOAD_GDAL:If set, use the gdal driver for loading the image.(默認)
IMREAD_REDUCED_GRAYSCALE_2:如果設置了這個,圖像總是轉換爲單通道灰度圖,且尺寸縮減爲1/2
IMREAD_REDUCED_COLOR_2:圖像總是轉換爲彩色3通道BGR且尺寸縮減爲1/2.
IMREAD_REDUCED_GRAYSCALE_4:同上,灰度,縮減爲1/4
IMREAD_REDUCED_COLOR_4:同上,彩色,縮減爲1/4
IMREAD_REDUCED_GRAYSCALE_8:同上,灰度,縮減爲1/8
IMREAD_REDUCED_COLOR_8:同上,彩色,縮減爲1/8
對攝像頭的操作
import cv2
def video_demo():
# 0是代表攝像頭編號,只有一個的話默認爲0
capture = cv2.VideoCapture(0)
if capture.isOpened():
print("攝像頭已經連接")
while True:
# ret:是否成功讀取幀,布爾值
# frame:幀本身的值
ret, frame = capture.read()
# print("type-frame:", type(frame)) # numpy.ndarray
# print("shape-frame:", np.shape(frame)) # (480, 640, 3)
# print("ret: ", ret) # True
# 窗口的名稱爲"camera",顯示攝像頭中的內容
cv2.imshow("camera", frame)
# cv.imshow("camera", frame[10:300, 50:400]) # 截取攝像頭的攝像範圍
# 按“Esc”退出
if cv2.waitKey(30) & 0xff == 27:
capture.release()
break
else:
print("未檢測到攝像頭")
video_demo()
cv2.waitKey()
cv2.destroyAllWindows()