行空版优雅的实现拍照功能
思路
- 将摄像头图片存入文件,调用ui库显示文件图片
- 直接传入图片数据
细节
OpenCV中摄像头需要打开视频流VideoCapture
才能获取图片,打开有耗时,若每次拍照都打开一次,会浪费资源
解决
启动时,创建线程打开视频流并不断读取帧图片,需要时取出
方法:
Camera.py
import cv2
from PIL import Image
class Camera:
frame = None
def startCapture(self):
print("Start Video Capture")
self.capture = cv2.VideoCapture(0)
hasFrame = True
while hasFrame:
hasFrame, frame = self.capture.read()
self.frame = frame
print("Capture end")
def capturePhoto(self):
# 转为ui库支持的格式
return Image.fromarray(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB))
UI.py
from unihiker import GUI
from Camera import Camera
class BoatUI:
def __init__(self):
self.gui = GUI()
self.camera = Camera()
def _capturePhoto(self):
self.updateImageWidget(self.camera.capturePhoto())
def capturePhoto(self):
self.gui.start_thread(self._capturePhoto)
def updateImageWidget(self, newImage):
self.imageWidget = self.gui.draw_image(x=120, y=250, w=220, h=165, image=newImage, origin='center')
def show(self):
self.gui.add_button(x=120, y=130, w=100, h=30, text="拍照", origin="center", onclick=self.capturePhoto)
# 创建获取视频流线程
self.gui.start_thread(self.camera.startCapture)
显示UI
main.py
import time
import BoatUI
import Controller
if __name__ == "__main__":
boatUi = BoatUI.BoatUI()
boatUi.show()
print("UI Showed")
while True:
time.sleep(1)
更多
本人第一次写python并面对对象,若有错误欢迎指出