新しいバージョンのjupyter labはjupyter_clickable_image_widgetを使うと実際表示されないようです。なのでipycanvasを使いました。クリックイベントほか、画像描画などにも使えます。
ipycanvasをインストールします。
pip install ipycanvas
nodeはVersion20以上
node -v
jupyterlabを拡張します。
jupyter labextension install @jupyter-widgets/jupyterlab-manager
jupyter labextension install ipycanvas
ビルドします。
jupyter lab build
再起動します。
jupyter lab
from ipycanvas import Canvas
from IPython.display import display
import ipywidgets as widgets
import cv2
# 元画像読み込み&縮小
image_path = '/home/jetson/jetracer/notebooks/camera/test202503292022/xy/0_0_00063.jpg'
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_resized = cv2.resize(img, (224, 224)) # ピクセル的に縮小
# キャンバスサイズは縮小画像と一致
canvas = Canvas(width=224, height=224)
canvas.put_image_data(img_resized)
# 見た目サイズを強制縮小
canvas_widget = widgets.Box([canvas], layout=widgets.Layout(width='224px', height='224px'))
# 座標表示
x_widget = widgets.IntText(description='x')
y_widget = widgets.IntText(description='y')
log_output = widgets.Output()
# クリック時処理
def handle_click(x, y):
with log_output:
print(f"Clicked at: ({x}, {y})")
x_widget.value = int(x)
y_widget.value = int(y)
canvas.clear()
canvas.put_image_data(img_resized)
canvas.fill_style = 'green'
canvas.fill_circle(x, y, 3)
canvas.on_mouse_down(lambda x, y: handle_click(x, y))
# UI 表示
ui = widgets.VBox([
canvas_widget,
widgets.HBox([x_widget, y_widget]),
log_output
])
display(ui)