import streamlit as st
from PIL import Image, ImageDraw
import io
def image_to_bytes(image):
img_bytes = io.BytesIO()
image.save(img_bytes, format='JPEG')
return img_bytes.getvalue()
def calculate_coordinates(points):
min_x = min(points, key=lambda x: x[0])[0]
min_y = min(points, key=lambda x: x[1])[1]
max_x = max(points, key=lambda x: x[0])[0]
max_y = max(points, key=lambda x: x[1])[1]
return (min_x, min_y, max_x, max_y)
st.title("Image Crop Tool")
uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_image is not None:
image = Image.open(uploaded_image)
col1, col2 = st.beta_columns(2)
with col1:
st.header("Original Image")
st.image(image, use_column_width=True)
with col2:
st.header("Selected Bounding Box")
draw = ImageDraw.Draw(image)
points = [(0, 0), (100, 0), (100, 100), (0, 100)]
draw.polygon(points, outline="red")
st.image(image, use_column_width=True)
st.subheader("Select 3 or 4 points on the image")
points_input = []
points_input.append(tuple(map(int, st.text_input("Point 1 (x, y):").split(','))))
points_input.append(tuple(map(int, st.text_input("Point 2 (x, y):").split(','))))
points_input.append(tuple(map(int, st.text_input("Point 3 (x, y):").split(','))))
fourth_point = st.text_input("Point 4 (x, y, optional):")
if fourth_point:
points_input.append(tuple(map(int, fourth_point.split(','))))
if st.button("Show Coordinates"):
if len(points_input) >= 3:
coordinates = calculate_coordinates(points_input)
st.write(f"Coordinates: {coordinates}")
cropped_image = image.crop(coordinates)
st.write("Cropped Image:")
st.image(cropped_image, use_column_width=True)
else:
st.error("Please enter at least 3 points.")
else:
st.info("Please upload an image.")
This app allows the user to upload an image, click at least 3 points on the image, crop the image, and print out the coordinates.