如何在Streamlit中将相机输入与输出改为横向并排布局
解决方案:调整Streamlit相机输入与输出布局及缩小相机控件宽度
针对你提出的两个需求,这里给出具体的代码修改方案:
1. 实现输入输出横向并排布局
使用Streamlit的st.columns()方法创建两列容器,分别放置原始相机图像和卡通化后的输出图像,即可实现横向并排效果。
2. 缩小st.camera_input的宽度
Streamlit原生没有直接设置相机控件宽度的参数,但可以通过两种方式实现:
- 方法一:用列容器限制宽度:创建宽度比例更小的列,将相机控件放入其中
- 方法二:自定义CSS样式:通过
st.markdown()注入CSS代码直接修改控件宽度
下面是整合两种需求的完整修改代码:
import cv2 import streamlit as st import numpy as np from PIL import Image def cartoonization(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 7) edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 7) blurred = cv2.bilateralFilter(img, d=7, sigmaColor=200,sigmaSpace=200) cartoon = cv2.bitwise_and(blurred, blurred, mask=edges) return cartoon # 自定义CSS缩小相机控件宽度(可选,和方法一二选一) # st.markdown(""" # <style> # div[data-testid="stCameraInput"] { # width: 50%; # } # </style> # """, unsafe_allow_html=True) # 方法一:用列限制相机控件宽度(占页面1/3宽度) col_camera, _ = st.columns([1, 2]) with col_camera: file_image = st.camera_input(label="Take a pic of you to be sketched out") if file_image: input_img = Image.open(file_image) final_sketch = cartoonization(np.array(input_img)) # 创建两列实现横向并排布局 col1, col2 = st.columns(2) with col1: st.write("**Input Photo**") st.image(input_img, use_column_width=True) with col2: st.write("**Output Cartoon Image**") st.image(final_sketch, use_column_width=True) else: st.write("You haven't uploaded any image file")
关键修改说明
缩小相机控件宽度:
- 代码中用
st.columns([1,2])创建了宽度比例为1:2的两列,将相机输入放在第一列(占1/3页面宽度),如果需要更窄的宽度,可以调整比例,比如[1,3]会让相机控件占1/4宽度。 - 如果你更喜欢用CSS自定义,可以取消注释代码中的CSS部分,修改
width: 50%;为你需要的百分比,比如30%。
- 代码中用
横向并排布局:
- 当获取到相机图像后,创建
col1, col2 = st.columns(2)两列,分别在列内放置原始图像和卡通化结果,实现左右并排显示,同时添加了对应的标题区分。
- 当获取到相机图像后,创建
内容的提问来源于stack exchange,提问作者sayile firahs
相关产品推荐
相关产品推荐

