如何修改Streamlit应用背景?尝试代码无效果求解决方案
如何修改Streamlit应用的背景图片?
你之前的代码没生效,是因为Streamlit的页面布局中,实际承载应用内容的容器是.stApp而非body,直接设置body的背景会被上层元素的背景覆盖。以下是可行的修改方案:
修正后的背景设置代码
替换你原来的CSS片段,使用.stApp作为选择器,同时可调整主内容区的背景透明度,让背景图正常显示:
page_bg_img = ''' <style> .stApp { background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366"); background-size: cover; background-position: center; } /* 可选:调整主内容区域背景透明度,避免遮挡背景 */ .stMainBlockContainer { background-color: rgba(255, 255, 255, 0.8); border-radius: 8px; padding: 1rem; } </style> ''' st.markdown(page_bg_img, unsafe_allow_html=True)
整合到你的完整应用代码
把这段背景设置代码放在导入库之后、业务逻辑之前,完整代码如下:
import cv2 import streamlit as st import numpy as np from PIL import Image # 设置背景图片 page_bg_img = ''' <style> .stApp { background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366"); background-size: cover; background-position: center; } .stMainBlockContainer { background-color: rgba(255, 255, 255, 0.8); border-radius: 8px; padding: 1rem; } </style> ''' st.markdown(page_bg_img, unsafe_allow_html=True) def cartoonization (img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 9) edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) color = cv2.detailEnhance(img, sigma_s=10, sigma_r=0.15) cartoon = cv2.bitwise_and(color, color, mask=edges) return cartoon st.write(""" # Cartoonize Your Image! """ ) st.write("This is an app to turn your photos into cartoon") 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)) st.write("**Output Pencil Sketch**") st.image(final_sketch, use_column_width=True) else: st.write("You haven't uploaded any image file")
说明
.stApp是Streamlit应用的根容器,设置它的背景图才能覆盖整个页面- 额外添加的
.stMainBlockContainer样式是为了让主内容区背景半透明,既保留背景图可见,又保证内容可读性,你可根据需求调整rgba的透明度值(最后一个参数在0-1之间)
内容的提问来源于stack exchange,提问作者sayile firahs
相关产品推荐
相关产品推荐

