import streamlit as st
import base64
import requests
from PIL import Image
import io
# 百度智慧云API的API Key和Secret Key
API_KEY = 'DnE8FI0luW1SigJ53wqyVd8I'
SECRET_KEY = 'fDUfEDmeJk5MVhCfcRmOW0pmVfw1f35e'
# 获取Access Token
def get_access_token():
url = "https://aip.baidubce.com/oauth/2.0/token?client_id=DnE8FI0luW1SigJ53wqyVd8I&client_secret=fDUfEDmeJk5MVhCfcRmOW0pmVfw1f35e&grant_type=client_credentials"
params = {
"grant_type": "client_credentials",
"client_id": API_KEY,
"client_secret": SECRET_KEY
}
response = requests.get(url, params=params)
if response.ok:
return response.json().get('access_token')
return None
# 编码图像为Base64
def encode_image_to_base64(image):
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
encoded_image = base64.b64encode(buffered.getvalue())
return encoded_image.decode('utf-8')
# 解码Base64字符串为图像对象
def decode_base64_to_image(encoded_string):
# 将 base64 编码的字符串转换为字节串
decoded_bytes = base64.b64decode(encoded_string)
# 将字节串转换为图像对象
image = Image.open(io.BytesIO(decoded_bytes))
return image
# 发送请求到百度智慧云API
def send_request(url, params, access_token):
headers = {
'Content-Type': 'application/json'
}
url = f"{url}?access_token={access_token}"
response = requests.post(url, headers=headers, json=params)
if response:
return response.json()
return None
# 动态获取图片大小
def get_dynamic_rectangle(image):
# 获取图像大小
width, height = image.size
# 计算矩形区域的左上角和右下角坐标
top_left_x = 0
top_left_y = 0
bottom_right_x = width
bottom_right_y = height
# 返回矩形区域坐标
return f"{top_left_x},{top_left_y},{bottom_right_x},{bottom_right_y}"
# 图像修复
def image_repair(image, access_token):
image_base64 = encode_image_to_base64(image)
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/inpainting"
params = {
"image": image_base64,
"rectangle": get_dynamic_rectangle(image) # 动态获取矩形区域
}
st.info("调用图像修复API...")
return send_request(url, params, access_token)
# 人物动漫化
def cartoonize(image, access_token):
image_base64 = encode_image_to_base64(image)
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
params = {
"image": image_base64
}
st.info("调用人物动漫化API...")
return send_request(url, params, access_token)
# 图像清晰度增强
def enhance_image(image, access_token):
image_base64 = encode_image_to_base64(image)
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance"
params = {
"image": image_base64
}
st.info("调用图像清晰度增强API...")
return send_request(url, params, access_token)
# 图像风格转换
def style_transfer(image, access_token, style='cartoon'):
image_base64 = encode_image_to_base64(image)
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans"
params = {
"image": image_base64,
"option": style
}
st.info("调用图像风格转换API...")
return send_request(url, params, access_token)
# 拉伸图像恢复
def stretch_restore(image, access_token):
image_base64 = encode_image_to_base64(image)
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/stretch_restore"
params = {
"image": image_base64
}
st.info("调用拉伸图像恢复API...")
return send_request(url, params, access_token)
# 主函数
def main():
st.title("照片修复程序设计")
st.write("请选择一个图像文件,并选择一个功能进行处理")
# 获取 Access Token
access_token = get_access_token()
if not access_token:
st.error("获取 Access Token 失败")
return
# 文件上传
uploaded_file = st.file_uploader("选择一个图像文件", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='上传的图像', use_column_width=True)
st.write("请选择要执行的功能:")
option = st.selectbox(
'',
('图像修复', '人物动漫化', '图像清晰度增强', '图像风格转换', '拉伸图像恢复')
)
if st.button('执行'):
result = None
if option == '图像修复':
result = image_repair(image, access_token)
elif option == '人物动漫化':
result = cartoonize(image, access_token)
elif option == '图像清晰度增强':
result = enhance_image(image, access_token)
elif option == '图像风格转换':
style = st.text_input("请输入风格类型(例如:cartoon):", value='cartoon')
result = style_transfer(image, access_token, style)
elif option == '拉伸图像恢复':
result = stretch_restore(image, access_token)
if result:
st.write(f"{option} 结果:", result)
if 'image' in result:
img_data = result['image']
img = decode_base64_to_image(img_data)
st.image(img, caption=f'{option} 结果', use_column_width=True)
else:
st.error(f"{option} 处理失败")
# 示例: 运行主函数
if __name__ == "__main__":
main()
浙公网安备 33010602011771号