import gradio as gr from PIL import Image def change_background_to_white(image): try: # 이미지를 RGBA로 변환하여 알파 채널을 확보 rgba_image = image.convert('RGBA') except Exception as e: return None, f"이미지 처리 중 오류가 발생했습니다: {str(e)}" # 고해상도 이미지에 대한 경고 if rgba_image.width > 3000 or rgba_image.height > 3000: return None, "매우 큰 이미지는 처리 시간이 길어질 수 있습니다. 가능하다면 이미지 크기를 줄여주세요." # 새로운 흰색 배경 이미지 생성 white_bg = Image.new('RGBA', rgba_image.size, (255, 255, 255, 255)) # 원본 이미지의 픽셀 데이터를 가져옴 pixels = rgba_image.getdata() # 새로운 픽셀 데이터 리스트 생성 new_pixels = [] # 모든 픽셀을 순회하며 투명한 부분을 흰색으로 변경 for pixel in pixels: if pixel[3] < 255: new_pixels.append((255, 255, 255, 255)) # 투명한 부분을 흰색으로 변경 else: new_pixels.append(pixel) # 변경된 픽셀 데이터로 이미지를 업데이트 white_bg.putdata(new_pixels) # 최종 이미지를 RGB로 변환하여 반환 final_image = white_bg.convert('RGB') return final_image, "이미지 처리가 완료되었습니다." with gr.Blocks() as app: gr.Markdown("## 이미지의 배경색을 흰색으로 변경하기") with gr.Row(): input_image = gr.Image(type="pil", label="이미지 업로드") output_image = gr.Image(label="배경색 변경된 이미지") output_text = gr.Textbox(label="처리 결과") input_image.change(fn=change_background_to_white, inputs=input_image, outputs=[output_image, output_text]) if __name__ == "__main__": app.launch()