Fletで画像上に矩形を描画し、その座標を取得できるクロッピングコンテナを作成します。
import flet as ft
from PIL import Image
import os
class CroppingContainer(ft.UserControl):
def __init__(self, image_path, width=400, height=400, on_crop_change=None):
super().__init__()
self.image_path = image_path
self.container_width = width
self.container_height = height
self.on_crop_change = on_crop_change
# 画像の実際のサイズを取得
with Image.open(image_path) as img:
self.original_width, self.original_height = img.size
# 矩形の座標(コンテナ内での相対座標)
self.rect_start_x = 0
self.rect_start_y = 0
self.rect_end_x = 0
self.rect_end_y = 0
self.is_drawing = False
def build(self):
# 画像を表示するコンテナ
self.image_container = ft.Container(
width=self.container_width,
height=self.container_height,
image_src=self.image_path,
image_fit=ft.ImageFit.CONTAIN,
bgcolor=ft.colors.BLACK12,
)
# 矩形を描画するキャンバス
self.canvas = ft.Canvas(
width=self.container_width,
height=self.container_height,
shapes=[],
)
# ジェスチャー検出用のコンテナ
self.gesture_detector = ft.GestureDetector(
on_pan_start=self.on_pan_start,
on_pan_update=self.on_pan_update,
on_pan_end=self.on_pan_end,
content=ft.Stack([
self.image_container,
self.canvas,
]),
)
return self.gesture_detector
def on_pan_start(self, e: ft.DragStartEvent):
self.is_drawing = True
self.rect_start_x = e.local_x
self.rect_start_y = e.local_y
self.rect_end_x = e.local_x
self.rect_end_y = e.local_y
self.update_rectangle()
def on_pan_update(self, e: ft.DragUpdateEvent):
if self.is_drawing:
self.rect_end_x = e.local_x
self.rect_end_y = e.local_y
self.update_rectangle()
def on_pan_end(self, e: ft.DragEndEvent):
self.is_drawing = False
if self.on_crop_change:
crop_coords = self.get_crop_coordinates()
self.on_crop_change(crop_coords)
def update_rectangle(self):
# 矩形を描画
x = min(self.rect_start_x, self.rect_end_x)
y = min(self.rect_start_y, self.rect_end_y)
width = abs(self.rect_end_x - self.rect_start_x)
height = abs(self.rect_end_y - self.rect_start_y)
self.canvas.shapes = [
ft.canvas.Rect(
x=x,
y=y,
width=width,
height=height,
paint=ft.Paint(
stroke_width=2,
style=ft.PaintingStyle.STROKE,
color=ft.colors.RED,
),
)
]
self.canvas.update()
def get_crop_coordinates(self):
"""実際の画像座標系での矩形の座標を返す [x1, x2, y1, y2]"""
# コンテナ内での矩形の座標を正規化
x1 = min(self.rect_start_x, self.rect_end_x)
x2 = max(self.rect_start_x, self.rect_end_x)
y1 = min(self.rect_start_y, self.rect_end_y)
y2 = max(self.rect_start_y, self.rect_end_y)
# 画像のアスペクト比を考慮してスケーリング
img_aspect = self.original_width / self.original_height
container_aspect = self.container_width / self.container_height
if img_aspect > container_aspect:
# 画像の幅がコンテナに合わせられている
scale = self.container_width / self.original_width
display_height = self.original_height * scale
offset_y = (self.container_height - display_height) / 2
real_x1 = int(x1 / scale)
real_x2 = int(x2 / scale)
real_y1 = int((y1 - offset_y) / scale)
real_y2 = int((y2 - offset_y) / scale)
else:
# 画像の高さがコンテナに合わせられている
scale = self.container_height / self.original_height
display_width = self.original_width * scale
offset_x = (self.container_width - display_width) / 2
real_x1 = int((x1 - offset_x) / scale)
real_x2 = int((x2 - offset_x) / scale)
real_y1 = int(y1 / scale)
real_y2 = int(y2 / scale)
# 境界チェック
real_x1 = max(0, min(real_x1, self.original_width))
real_x2 = max(0, min(real_x2, self.original_width))
real_y1 = max(0, min(real_y1, self.original_height))
real_y2 = max(0, min(real_y2, self.original_height))
return [real_x1, real_x2, real_y1, real_y2]
def cropping_container(image_path, width=400, height=400, on_crop_change=None):
"""
画像をパス経由で渡すと、コンテナいっぱいに画像を表示し、その画像上に矩形を表示する
Args:
image_path: 画像ファイルのパス
width: コンテナの幅
height: コンテナの高さ
on_crop_change: 矩形が変更されたときのコールバック関数
Returns:
CroppingContainer: クロッピングコンテナのインスタンス
"""
return CroppingContainer(image_path, width, height, on_crop_change)
# 使用例
def main(page: ft.Page):
page.title = "Image Cropping Container"
def on_crop_change(coords):
crop_info.value = f"Crop coordinates: x1={coords[0]}, x2={coords[1]}, y1={coords[2]}, y2={coords[3]}"
page.update()
# 画像パスを指定
image_path = "sample.jpg" # 実際の画像パスに変更してください
# クロッピングコンテナを作成
cropper = cropping_container(
image_path=image_path,
width=600,
height=400,
on_crop_change=on_crop_change
)
crop_info = ft.Text("ドラッグして矩形を描画してください")
page.add(
ft.Column([
cropper,
crop_info,
])
)
if __name__ == "__main__":
ft.app(target=main)
このコードの主な機能:
-
画像表示: 指定されたパスの画像をコンテナいっぱいに表示(アスペクト比を保持)
-
矩形描画: マウスドラッグで赤い矩形を描画
-
座標取得: get_crop_coordinates()メソッドで実際の画像座標系での矩形の座標を[x1, x2, y1, y2]形式で取得
-
コールバック: on_crop_changeパラメータで矩形が変更されたときの処理を指定可能
使い方:
# クロッピングコンテナを作成
cropper = cropping_container(
image_path="path/to/image.jpg",
width=600,
height=400,
on_crop_change=lambda coords: print(f"選択範囲: {coords}")
)
# 現在の選択範囲を取得
current_coords = cropper.get_crop_coordinates()
注意点:
- PILライブラリが必要です(
pip install Pillow)
- 画像のアスペクト比を考慮して、実際の画像座標に変換しています
- 矩形は画像の境界内に制限されます