はじめに
streamlit-draw-canvasで矩形および点を描画していきます
開発環境
- Windows 11 PC
- Python 3.11
- Streamlit
導入
ライブラリをインストール
pip install streamlit
pip install streamlit-drawable-canvas
実行方法
streamlit run filename.py
http://localhost:8501/ にアクセス
矩形の描画
drawable-canvas-rect.py
import streamlit as st
from streamlit_drawable_canvas import st_canvas
# Streamlit app タイトル
st.title("Drawable Canvas Demo")
# キャンバスの設定
canvas_result = st_canvas(
fill_color="rgba(255, 165, 0, 0.3)", # 塗りつぶしの色
stroke_width=2, # 線の太さ
stroke_color="#000000", # 線の色
background_color="#FFF", # 背景色
background_image=None, # 背景画像(なし)
update_streamlit=True, # Streamlitをリアルタイムで更新
height=150, # キャンバスの高さ
drawing_mode="rect", # 描画モード(矩形)
key="canvas", # キャンバスのキー
)
# 描画結果の表示
if canvas_result.json_data is not None:
st.json(canvas_result.json_data)
{
"version": "4.4.0",
"objects": [],
"background": "#FFF"
}
{
"version": "4.4.0",
"objects": [
{
"type": "rect",
"version": "4.4.0",
"originX": "left",
"originY": "top",
"left": 181,
"top": 21,
"width": 137,
"height": 96,
"fill": "rgba(255, 165, 0, 0.3)",
"stroke": "#000000",
"strokeWidth": 2,
"strokeDashArray": null,
"strokeLineCap": "butt",
"strokeDashOffset": 0,
"strokeLineJoin": "miter",
"strokeUniform": true,
"strokeMiterLimit": 4,
"scaleX": 1,
"scaleY": 1,
"angle": 0,
"flipX": false,
"flipY": false,
"opacity": 1,
"shadow": null,
"visible": true,
"backgroundColor": "",
"fillRule": "nonzero",
"paintFirst": "fill",
"globalCompositeOperation": "source-over",
"skewX": 0,
"skewY": 0,
"rx": 0,
"ry": 0
}
],
"background": "#FFF"
}
点の描画
drawable-canvas-point.py
import streamlit as st
from streamlit_drawable_canvas import st_canvas
# Streamlitアプリケーションのタイトルを設定
st.title("Drawable Canvas Demo")
# Drawable Canvasを表示し、背景画像のサイズに合わせて高さと幅を設定
canvas_result = st_canvas(
fill_color="rgba(255, 165, 0, 0.3)", # 描画色
stroke_width=5, # 線の太さ
stroke_color="rgb(255, 165, 0)", # 線の色
background_color="#FFF", # 背景色
background_image=None, # 背景画像(なし)
update_streamlit=True, # Streamlitをリアルタイムで更新
height=150, # キャンバスの高さ
drawing_mode="point", # 描画モード(点)
)
# 描画結果の表示
if canvas_result.json_data is not None:
st.json(canvas_result.json_data)
{
"version": "4.4.0",
"objects": [
{
"type": "circle",
"version": "4.4.0",
"originX": "left",
"originY": "center",
"left": 149.5,
"top": 95,
"width": 6,
"height": 6,
"fill": "rgba(255, 165, 0, 0.3)",
"stroke": "rgb(255, 165, 0)",
"strokeWidth": 5,
"strokeDashArray": null,
"strokeLineCap": "butt",
"strokeDashOffset": 0,
"strokeLineJoin": "miter",
"strokeUniform": false,
"strokeMiterLimit": 4,
"scaleX": 1,
"scaleY": 1,
"angle": 0,
"flipX": false,
"flipY": false,
"opacity": 1,
"shadow": null,
"visible": true,
"backgroundColor": "",
"fillRule": "nonzero",
"paintFirst": "fill",
"globalCompositeOperation": "source-over",
"skewX": 0,
"skewY": 0,
"radius": 3,
"startAngle": 0,
"endAngle": 6.283185307179586
}
],
"background": "#FFF"
}
お疲れさまでした。