import cv2
import streamlit as st
import numpy as np
from PIL import Image, ImageEnhance


def adjust_image(image, brightness, contrast, saturation):
    # Adjust brightness and contrast
    adjusted_image = cv2.convertScaleAbs(image, alpha=contrast, beta=brightness)
    adjusted_image = np.clip(adjusted_image, 0, 255)
    # Adjust saturation
    image_hsv = cv2.cvtColor(adjusted_image, cv2.COLOR_BGR2HSV)
    image_hsv[:, :, 1] = np.clip(image_hsv[:, :, 1] * saturation, 0, 255)
    adjusted_image = cv2.cvtColor(image_hsv, cv2.COLOR_HSV2BGR)
    
    return adjusted_image

def halftone (image):
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Set the size of the halftone dots
    dot_size = 1  # Adjust this value to control dot size

    # Create a blank canvas for the halftone effect
    halftone = np.zeros_like(gray_image)

    # Apply halftone effect by thresholding the image
    for i in range(0, gray_image.shape[0], dot_size):
        for j in range(0, gray_image.shape[1], dot_size):
            roi = gray_image[i:i+dot_size, j:j+dot_size]
            mean_val = np.mean(roi)
            halftone[i:i+dot_size, j:j+dot_size] = 255 if mean_val > 128 else 0

    return halftone



def main():


    st.title("Image processing for Screen Printing")
    st.subheader("Work in progress")
    # Sidebar
    

    st.sidebar.title("Adjustment")

    brightness = st.sidebar.slider("Brightness", -100, 100, 0)
    contrast = st.sidebar.slider("Contrast", 0.1, 3.0, 1.0)
    saturation = st.sidebar.slider("Saturation", 0.1, 3.0, 1.0)

    image = st.sidebar.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])

        

    if not image:
        return None
    

   

    # central app

    

    image = cv2.imdecode(np.fromstring(image.read(), np.uint8), cv2.IMREAD_COLOR)
    
    

    adjusted_image = adjust_image(image, brightness, contrast, saturation)

    #adjusted_image = np.array(halftoned)
        
    col1, col2 = st.columns(2)

    with col1:
        st.header("Original Image")
        st.image(image, caption="Original Image", use_column_width=True, channels="BGR")

    with col2:
        st.header("Processed Image")
        st.image(adjusted_image, caption="Processed Image", use_column_width=True, channels="BGR")

    st.image(halftone(image))




if __name__ == '__main__':
    main()