0<0# : ^
'''
@echo off
set script=%~f0
python -x "%script%" %*
exit /b 0
'''
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk, ImageDraw
def get_transparency_color(image_path):
image = Image.open(image_path)
transparency_color = image.getpixel((image.width - 1, image.height - 1))
return transparency_color
def find_non_transparent_bbox(image_path, transparency_color):
image = Image.open(image_path)
image_data = image.load()
width, height = image.size
left, top, right, bottom = width, height, 0, 0
for y in range(height):
for x in range(width):
if image_data[x, y] != transparency_color:
left = min(left, x)
top = min(top, y)
right = max(right, x)
bottom = max(bottom, y)
if left == width and top == height and right == 0 and bottom == 0:
return None
return left, top, right, bottom
def convert_bbox_to_bbox_format(bbox):
left, top, right, bottom = bbox
width = right - left + 1
height = bottom - top + 1
return left, top, width, height
def draw_bbox(image, bbox):
image_draw = ImageDraw.Draw(image)
left, top, right, bottom = bbox
image_draw.rectangle([left, top, right, bottom], outline=(0, 0, 255), width=2, fill=None)
return image
def upload_image():
file_path = filedialog.askopenfilename()
if file_path:
transparency_color = get_transparency_color(file_path)
image = Image.open(file_path)
if image.mode != "RGBA":
image = image.convert("RGBA")
bbox = find_non_transparent_bbox(file_path, transparency_color)
if bbox:
bbox_format = convert_bbox_to_bbox_format(bbox)
bbox_command = f"bbox {bbox_format[0]} {bbox_format[1]} {bbox_format[2]} {bbox_format[3]}"
bbox_entry.delete(0, tk.END)
bbox_entry.insert(0, bbox_command)
max_size = (400, 400)
image.thumbnail(max_size, Image.NEAREST)
image_with_bbox = draw_bbox(image.copy(), bbox)
photo = ImageTk.PhotoImage(image_with_bbox)
canvas.image = photo
canvas.create_image(0, 0, anchor=tk.NW, image=photo)
else:
bbox_entry.delete(0, tk.END)
bbox_entry.insert(0, "No non-transparent pixels found.")
root = tk.Tk()
root.title("BBOX Creator")
upload_button = tk.Button(root, text="Upload Image", command=upload_image)
upload_button.pack()
bbox_entry = tk.Entry(root, width=50)
bbox_entry.pack()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
root.mainloop()