下面的方法實現了,從攝像頭獲取圖片,並根據條件翻轉或旋轉
import cv2
# flip_x, flip_y 分別決定了是否進行x軸翻轉 y軸翻轉
# clip = (x,y,w,h);左上角坐標及寬高 決定了要裁剪的方形區域; 不進行裁剪則全部置0
# rotate: 0不旋轉; 1 順時針轉90度; 2 旋轉180度; -1 逆時針旋轉90度
def take_picture(flip_x=False, flip_y=False, clip=(0, 0, 100, 100), rotate=0):
clip_x, clip_y, clip_w, clip_h = clip
cap = cv2.VideoCapture(0)
# print("set pic width: ", cap.set(3, 3664))
# print("set pic height: ", cap.set(4, 2748), rotate, flip_x)
res, frame = cap.read()
cap.release()
if res:
cv2.imwrite("images/origin.png", frame)
if flip_x:
frame = cv2.flip(frame, 1)
if flip_y:
frame = cv2.flip(frame, 0)
if rotate:
frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE if rotate == 1 else cv2.ROTATE_90_COUNTERCLOCKWISE if rotate == -1 else cv2.ROTATE_180)
if flip_x or flip_y or rotate:
cv2.imwrite("images/res_rotate", frame)
if clip_x or clip_y or clip_w or clip_h:
img = frame[clip_y: clip_y + clip_h, clip_x: clip_x + clip_w]
cv2.imwrite("images/res_clip.png", img)
else:
cv2.imwrite("images/res_clip.png.png", frame)
return True
else:
return False