拍照上传 Google 云端硬盘
这篇教学会运用 OpenCV 进行拍照或截图,并搭配“上传文件到 Google 云端硬盘”教学的做法,将摄影机镜头抓取的图像,即时传送到 Google 云端硬盘进行备份。
快速导览:
因为程序中的 OpenCV 会需要使用镜头或 GPU,所以请使用本机环境 ( 参考:使用 Python 虚拟环境 ) 或使用 Anaconda Jupyter 进行实作 ( 参考:使用 Anaconda ) ,并安装 OpenCV 函数库 ( 参考:OpenCV 函数库 )。
使用摄影机拍照
参考“打开并显示图片”和“写入并储存图片”两篇教学,撰写下列的程序码,执行后会打开摄影机,按下键盘的空白键就会将当前的画面储存为一张 jpg 图档。
import cv2
cap = cv2.VideoCapture(0) # 啟用鏡頭
n = 1 # 照片起始編號
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read() # 讀取影片的每一幀
if not ret:
print("Cannot receive frame") # 如果讀取錯誤,印出訊息
break
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) # 轉換顏色為 BGRA
key = cv2.waitKey(1)
if key == 32: # 按下空白就截圖存檔
cv2.imwrite(f'photo-{n}.jpg', img) # 存檔
n = n + 1 # 編號增加 1
elif key == ord('q'): # 按下 q 結束
break
cv2.imshow('oxxostudio', img) # 顯示圖片
cap.release() # 所有作業都完成後,釋放資源
cv2.destroyAllWindows() # 結束所有視窗
上传照片到 Google 云端硬盘 ( 图片文件 )
能够拍照后,就能准备照片上传 Google 云端硬盘,上传的方法有两种,第一种是“将储存的照片上传”,参考下方程序码,当按下空白键时,就会拍照储存,接着就将储存的图片上传到 Google 云端硬盘,上传过程中由于程序码“同步”的缘故,画面会暂停等待上传完成后才会继续,如果需要使用“异步”的做法,请参考“threading 多执行绪处理”。
import cv2
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload
UPLOAD_FOLDER = '你的 Google 雲端資料夾 ID'
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = '金鑰檔案'
# 建立憑證
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=creds)
def upload(file):
filename = file
media = MediaFileUpload(filename) # 建立上傳檔案
file = {'name': filename, 'parents': [UPLOAD_FOLDER]}
print("正在上傳檔案...")
file_id = service.files().create(body=file, media_body=media).execute()
print('雲端檔案ID:' + str(file_id['id']))
cap = cv2.VideoCapture(0) # 啟用鏡頭
n = 1 # 照片起始編號
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read() # 讀取影片的每一幀
if not ret:
print("Cannot receive frame") # 如果讀取錯誤,印出訊息
break
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) # 轉換顏色為 BGRA
key = cv2.waitKey(1)
if key == 32: # 按下空白就截圖存檔
cv2.imwrite(f'photo-{n}.jpg', img) # 存檔
upload(f'photo-{n}.jpg') # 上傳檔案
n = n + 1 # 編號增加 1
elif key == ord('q'): # 按下 q 結束
break
cv2.imshow('oxxostudio', img) # 顯示圖片
cap.release() # 所有作業都完成後,釋放資源
cv2.destroyAllWindows() # 結束所有視窗
上传照片到 Google 云端硬盘 ( 二进制图片 )
第二种方法可以在拍照时,将图片转换成“二进制”文件格式,就能在“不储存”的状态下,直接将图片上传到 Google 云端硬盘,详细步骤请参考下方程序码:
import cv2, io
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload
UPLOAD_FOLDER = '你的 Google 雲端資料夾 ID'
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = '金鑰檔案'
# 建立憑證
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=creds)
def upload(image, filename):
jpg = cv2.imencode('.jpg', image)[1] # 將 numpy 陣列轉換成 jpg
imageBytes = io.BytesIO(jpg) # 將 jpg 轉換成二進位
media = MediaIoBaseUpload(imageBytes, mimetype='image/jpg', resumable=True)
file = {'name': filename, 'parents': [UPLOAD_FOLDER]}
print("正在上傳檔案...")
file_id = service.files().create(body=file, media_body=media).execute()
print('雲端檔案ID:' + str(file_id['id']))
cap = cv2.VideoCapture(0) # 啟用鏡頭
n = 1 # 照片起始編號
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read() # 讀取影片的每一幀
if not ret:
print("Cannot receive frame") # 如果讀取錯誤,印出訊息
break
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) # 轉換顏色為 BGRA
key = cv2.waitKey(1)
if key == 32: # 按下空白就截圖上傳
upload(img, f'photo-{n}.jpg') # 執行上傳函式
n = n + 1 # 編號增加 1
elif key == ord('q'): # 按下 q 結束
break
cv2.imshow('oxxostudio', img) # 顯示圖片
cap.release() # 所有作業都完成後,釋放資源
cv2.destroyAllWindows() # 結束所有視窗
使用摄影机录影
参考“读取并播放影片”和“写入并储存影片”两篇教学,撰写下列的程序码,执行后会打开摄影机,按下键盘的空白键就会开始录影,再按一次空白键就会结束录影,就可以不断按压空白键进行录影动作。
import cv2
cap = cv2.VideoCapture(0)
n = 1 # 存檔編號
record = -1 # 判斷是否開始錄影
fourcc = cv2.VideoWriter_fourcc(*"mp4v") # 設定影片的格式為 MP4 影片
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read() # 讀取影片的每一幀
width = img.shape[1] # 取得影像寬度
height = img.shape[0] # 取得影像高度
if not ret:
print("Cannot receive frame") # 如果讀取錯誤,印出訊息
break
key = cv2.waitKey(20)
if key == 32: # 按下空白就開始錄影
if record == -1:
output = cv2.VideoWriter(f'output-{n}.mp4', fourcc, 20.0, (width, height)) # 產生空的影片
n = n + 1 # 影片編號
record = record * -1
elif key == ord('q'): # 按下 q 結束
break
if record == 1:
output.write(img) # 寫入影像
print(record)
cv2.imshow('oxxostudio', img) # 顯示圖片
cap.release() # 所有作業都完成後,釋放資源
cv2.destroyAllWindows() # 結束所有視窗
上传影片到 Google 云端硬盘
能够录影后,就能准备影片上传 Google 云端硬盘,参考下方程序码,当按下空白键时,就会拍照储存,接着就将储存的影片上传到 Google 云端硬盘,上传过程中由于程序码“同步”的缘故,画面会暂停等待上传完成后才会继续,如果需要使用“异步”的做法,请参考“threading 多执行绪处理”。
import cv2
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload
UPLOAD_FOLDER = 'Google 雲端硬碟 ID'
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = '金鑰檔案'
# 建立憑證
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=creds)
def upload(file):
filename = file
media = MediaFileUpload(filename) # 建立上傳檔案
file = {'name': filename, 'parents': [UPLOAD_FOLDER]}
print("正在上傳檔案...")
file_id = service.files().create(body=file, media_body=media).execute()
print('雲端檔案ID:' + str(file_id['id']))
cap = cv2.VideoCapture(0) # 啟用鏡頭
n = 1 # 存檔編號
record = -1 # 判斷是否開始錄影
fourcc = cv2.VideoWriter_fourcc(*"mp4v") # 設定影片的格式為 MP4 影片
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read() # 讀取影片的每一幀
width = img.shape[1] # 取得影像寬度
height = img.shape[0] # 取得影像高度
if not ret:
print("Cannot receive frame") # 如果讀取錯誤,印出訊息
break
key = cv2.waitKey(20)
if key == 32: # 按下空白就開始錄影
if record == -1:
output = cv2.VideoWriter(f'output-{n}.mp4', fourcc, 20.0, (width, height)) # 產生空的影片
else:
upload(f'output-{n}.mp4') # 上傳檔案
n = n + 1 # 影片編號
record = record * -1
elif key == ord('q'): # 按下 q 結束
break
cv2.imshow('oxxostudio', img) # 顯示圖片
if record == 1:
output.write(img) # 寫入影像
print(record)
cap.release() # 所有作業都完成後,釋放資源
cv2.destroyAllWindows() # 結束所有視窗
微信扫码关注
抖音扫码关注