# src/tests/test_manual_crop_v2.py
from logging import getLogger
from logging.config import dictConfig
from pathlib import Path
from typing import Optional, Union, Callable, Tuple
import flet as ft
from PIL import Image
from configs.logging_config import LOGGING_CONFIG
from configs.path_config import EXAMPLE_IMAGE
logger_local = getLogger(__name__)
class CroppingContainer:
def __init__(
self,
src: Union[Path, str] = "",
on_rect_changed: Optional[Callable[[Tuple[int, int, int, int]], None]] = None
):
self.__src = str(src) if src else ""
self.__on_rect_changed = on_rect_changed
self.__image_actual_size: Optional[Tuple[int, int]] = None
self.__container_size: Optional[Tuple[float, float]] = None
self.__start_point: Optional[Tuple[float, float]] = None
self.__current_rect: Optional[Tuple[float, float, float, float]] = None # 表示上の座標
# UI要素の初期化
self.__image = ft.Image(
src=self.__src,
fit=ft.ImageFit.CONTAIN,
expand=True
)
self.__selection_rect = ft.Container(
bgcolor=ft.colors.with_opacity(0.3, ft.colors.BLUE),
border=ft.border.all(2, ft.colors.BLUE),
visible=False
)
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,
self.__selection_rect
],
expand=True
)
)
self.__container = ft.Container(
content=self.__gesture_detector,
expand=True,
on_resize=self.__on_container_resize
)
# 画像サイズの取得
if self.__src:
self.__load_image_info()
def __load_image_info(self):
"""画像の実際のサイズを取得"""
try:
with Image.open(self.__src) as img:
self.__image_actual_size = img.size # (width, height)
logger_local.debug(f"Loaded image size: {self.__image_actual_size}")
except Exception as e:
logger_local.error(f"Failed to load image info: {e}")
self.__image_actual_size = None
def __on_container_resize(self, e):
"""コンテナのリサイズイベント"""
if e.control.width and e.control.height:
self.__container_size = (e.control.width, e.control.height)
logger_local.debug(f"Container resized to: {self.__container_size}")
def __on_pan_start(self, e: ft.DragStartEvent):
"""ドラッグ開始"""
self.__start_point = (e.local_x, e.local_y)
self.__selection_rect.visible = True
self.__selection_rect.left = e.local_x
self.__selection_rect.top = e.local_y
self.__selection_rect.width = 0
self.__selection_rect.height = 0
self.__selection_rect.update()
def __on_pan_update(self, e: ft.DragUpdateEvent):
"""ドラッグ中"""
if not self.__start_point:
return
x1, y1 = self.__start_point
x2, y2 = e.local_x, e.local_y
# 矩形の位置とサイズを更新
left = min(x1, x2)
top = min(y1, y2)
width = abs(x2 - x1)
height = abs(y2 - y1)
self.__selection_rect.left = left
self.__selection_rect.top = top
self.__selection_rect.width = width
self.__selection_rect.height = height
self.__current_rect = (left, top, left + width, top + height)
self.__selection_rect.update()
def __on_pan_end(self, e: ft.DragEndEvent):
"""ドラッグ終了"""
if self.__on_rect_changed and self.__current_rect:
# 実際の画像座標に変換してコールバック呼び出し
actual_rect = self.__convert_to_image_coords(self.__current_rect)
if actual_rect:
self.__on_rect_changed(actual_rect)
def __convert_to_image_coords(self, display_rect: Tuple[float, float, float, float]) -> Optional[Tuple[int, int, int, int]]:
"""表示座標から実際の画像座標に変換"""
if not self.__image_actual_size or not self.__container_size:
return None
img_width, img_height = self.__image_actual_size
container_width, container_height = self.__container_size
# 画像のアスペクト比を保持した表示サイズを計算
img_aspect = img_width / img_height
container_aspect = container_width / container_height
if img_aspect > container_aspect:
# 幅に合わせる
display_width = container_width
display_height = container_width / img_aspect
offset_x = 0
offset_y = (container_height - display_height) / 2
else:
# 高さに合わせる
display_height = container_height
display_width = container_height * img_aspect
offset_x = (container_width - display_width) / 2
offset_y = 0
# スケール係数
scale_x = img_width / display_width
scale_y = img_height / display_height
# 表示座標から実際の画像座標に変換
x1 = int((display_rect[0] - offset_x) * scale_x)
y1 = int((display_rect[1] - offset_y) * scale_y)
x2 = int((display_rect[2] - offset_x) * scale_x)
y2 = int((display_rect[3] - offset_y) * scale_y)
# 範囲をクリップ
x1 = max(0, min(x1, img_width))
y1 = max(0, min(y1, img_height))
x2 = max(0, min(x2, img_width))
y2 = max(0, min(y2, img_height))
return (x1, x2, y1, y2)
def set_image(self, src: Union[Path, str]):
"""画像を設定"""
self.__src = str(src)
self.__image.src = self.__src
self.__load_image_info()
self.__selection_rect.visible = False
self.__current_rect = None
self.__image.update()
self.__selection_rect.update()
def set_rect(self, rect: Tuple[int, int, int, int]):
"""矩形を外部から設定(画像座標)"""
if not self.__image_actual_size or not self.__container_size:
return
x1, x2, y1, y2 = rect
img_width, img_height = self.__image_actual_size
container_width, container_height = self.__container_size
# 画像のアスペクト比を保持した表示サイズを計算
img_aspect = img_width / img_height
container_aspect = container_width / container_height
if img_aspect > container_aspect:
display_width = container_width
display_height = container_width / img_aspect
offset_x = 0
offset_y = (container_height - display_height) / 2
else:
display_height = container_height
display_width = container_height * img_aspect
offset_x = (container_width - display_width) / 2
offset_y = 0
# スケール係数
scale_x = display_width / img_width
scale_y = display_height / img_height
# 画像座標から表示座標に変換
display_x1 = x1 * scale_x + offset_x
display_y1 = y1 * scale_y + offset_y
display_x2 = x2 * scale_x + offset_x
display_y2 = y2 * scale_y + offset_y
self.__selection_rect.left = display_x1
self.__selection_rect.top = display_y1
self.__selection_rect.width = display_x2 - display_x1
self.__selection_rect.height = display_y2 - display_y1
self.__selection_rect.visible = True
self.__current_rect = (display_x1, display_y1, display_x2, display_y2)
self.__selection_rect.update()
@property
def container(self) -> ft.Container:
return self.__container
@property
def rect_area(self) -> Optional[Tuple[int, int, int, int]]:
"""現在選択されている矩形の画像座標を返す"""
if self.__current_rect:
return self.__convert_to_image_coords(self.__current_rect)
return None
def main(page: ft.Page):
page.window_width = 800
page.window_height = 600
# 選択範囲の表示用テキスト
rect_text = ft.Text("矩形未選択", size=16)
def on_rect_changed(rect: Tuple[int, int, int, int]):
rect_text.value = f"選択範囲: x1={rect[0]}, x2={rect[1]}, y1={rect[2]}, y2={rect[3]}"
rect_text.update()
logger_local.info(f"Rectangle changed: {rect}")
# CroppingContainerの作成
cropping_container = CroppingContainer(
src=EXAMPLE_IMAGE,
on_rect_changed=on_rect_changed
)
# テスト用:矩形を設定するボタン
def set_test_rect(e):
cropping_container.set_rect((100, 500, 100, 300))
rect_text.value = "矩形を設定しました: (100, 500, 100, 300)"
rect_text.update()
set_rect_button = ft.ElevatedButton("矩形を設定", on_click=set_test_rect)
# レイアウト
page.add(
ft.Column([
rect_text,
set_rect_button,
ft.Container(
content=cropping_container.container,
expand=True
)
], expand=True)
)
if __name__ == "__main__":
dictConfig(LOGGING_CONFIG)
ft.app(main)