Created
June 19, 2025 12:20
-
-
Save ochilab/1a8fa0eafde5a21db321d9884c016382 to your computer and use it in GitHub Desktop.
Fletでopencvのカメラ表示
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import base64 | |
import threading | |
import flet as ft | |
from io import BytesIO | |
from PIL import Image | |
# カメラ映像を定期的にキャプチャして画像を更新 | |
def camera_thread(page: ft.Page, image_control: ft.Image): | |
cap = cv2.VideoCapture(1) | |
while True: | |
ret, frame = cap.read() | |
if not ret: | |
continue | |
# OpenCVのBGRからPILのRGBへ変換 | |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
img_pil = Image.fromarray(frame) | |
# メモリにJPEGとして保存 → Base64エンコードしてFletに送る | |
buffer = BytesIO() | |
img_pil.save(buffer, format="JPEG") | |
img_str = base64.b64encode(buffer.getvalue()).decode() | |
# Flet UIの画像を更新 | |
image_control.src_base64 = img_str | |
page.update() | |
# Flet アプリのUI定義 | |
def main(page: ft.Page): | |
page.title = "OpenCV + Flet Camera Viewer" | |
image_control = ft.Image() | |
page.add(image_control) | |
# 別スレッドでカメラ処理開始 | |
threading.Thread(target=camera_thread, args=(page, image_control), daemon=True).start() | |
ft.app(target=main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment