PaushigaaInsifloAI/ComputerVisionBasics
0
1import gradio as gr2import cv23import numpy as np4 5def extract_color_channels(image, option):6 """Extracts individual color channels (BGR) from an image."""7 if option == 'Blue':8 image[:, :, 1] = 09 image[:, :, 2] = 010 return image11 elif option == 'Green':12 image[:, :, 0] = 013 image[:, :, 2] = 014 return image15 elif option == 'Red':16 image[:, :, 0] = 017 image[:, :, 1] = 018 return image19 20 21def convert_to_grayscale(image):22 """Converts an image to grayscale."""23 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)24 return gray_image25 26 27# Function to handle cropping28def crop_image(image, x, y, width, height):29 # Get the height and width of the image to ensure crop coordinates are valid30 img_height, img_width = image.shape[:2]31 32 # Adjusting if any input is outside image boundaries33 x = max(0, min(x, img_width))34 y = max(0, min(y, img_height))35 width = max(1, min(width, img_width - x))36 height = max(1, min(height, img_height - y))37 38 # Perform cropping39 cropped_image = image[y:y+height, x:x+width]40 return cropped_image41 42 43def apply_gaussian_blur(image, kernel_size=(15, 15)):44 """Applies Gaussian blur to an image."""45 blurred_image = cv2.GaussianBlur(image, kernel_size, 0)46 return blurred_image47 48 49def apply_blur_to_region(image, x, y, width, height):50 """Applies Gaussian blur to a specific region within an image."""51 mask = np.zeros(image.shape[:2], dtype=np.uint8)52 cv2.rectangle(mask, (x, y), (x + width, y + height), 255, -1)53 blurred_region = cv2.GaussianBlur(image, (15, 15), 0)54 blurred_region = cv2.bitwise_and(blurred_region, blurred_region, mask=mask)55 result_image = cv2.bitwise_and(image, image, mask=cv2.bitwise_not(mask))56 result_image = cv2.add(result_image, blurred_region)57 return result_image58 59 60def sharpen_image(image):61 """Sharpens an image using a kernel."""62 kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])63 sharpened_image = cv2.filter2D(image, -1, kernel)64 return sharpened_image65 66 67def apply_simple_thresholding(image, threshold_value=100):68 """Applies simple thresholding to a grayscale image."""69 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)70 ret, thresholded_image = cv2.threshold(gray_image, threshold_value, 255, cv2.THRESH_BINARY)71 return thresholded_image72 73 74def apply_adaptive_thresholding(image):75 """Applies adaptive thresholding to a grayscale image."""76 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)77 adaptive_thresholded_image = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,78 cv2.THRESH_BINARY, 11, 2)79 return adaptive_thresholded_image80 81 82def rotate_image(image, angle=33):83 """Rotates an image by a specified angle."""84 rows, cols = image.shape[:2]85 M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)86 rotated_image = cv2.warpAffine(image, M, (cols, rows))87 return rotated_image88 89 90def detect_borders_canny(image):91 """Detects borders using the Canny edge detection algorithm."""92 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)93 edges = cv2.Canny(gray_image, 50, 150)94 return edges95 96 97def segment_image(image):98 """Segments an image based on contours."""99 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)100 edges = cv2.Canny(gray_image, 50, 150)101 contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)102 segmented_image = np.zeros_like(image)103 for contour in contours:104 cv2.drawContours(segmented_image, [contour], -1, (0, 255, 0), -1)105 if contours:106 largest_contour = max(contours, key=cv2.contourArea)107 cv2.drawContours(segmented_image, [largest_contour], -1, (255, 0, 0), 2)108 mask = np.zeros_like(edges)109 cv2.drawContours(mask, [largest_contour], -1, 255, -1)110 outside_area = cv2.bitwise_and(image, image, mask=cv2.bitwise_not(mask))111 final_image = cv2.addWeighted(segmented_image, 1, outside_area, 1, 0)112 return final_image113 return segmented_image114 115def process_image(selected_function, image_file, color_channel=None, x=None, y=None, width=None, height=None, angle=None, x_blur=None, y_blur=None, height_blur=None, width_blur=None):116 image = cv2.imread(image_file.name)117 118 if selected_function == 'Display Image':119 display_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)120 return display_image121 122 elif selected_function == 'Extract Color Channel':123 channel = extract_color_channels(image, color_channel)124 channel = cv2.cvtColor(channel, cv2.COLOR_BGR2RGB)125 return channel # Color channel images don't need RGB conversion126 127 elif selected_function == 'Grayscale Conversion':128 gray_image = convert_to_grayscale(image)129 return gray_image130 131 elif selected_function == 'Crop Image':132 cropped_image = crop_image(image, x, y, width, height)133 cropped_image = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB)134 return cropped_image135 136 elif selected_function == 'Blur':137 gaussian_blur = apply_gaussian_blur(image)138 gaussian_blur = cv2.cvtColor(gaussian_blur, cv2.COLOR_BGR2RGB)139 return gaussian_blur140 141 elif selected_function == 'Blur a Region':142 region_blur = apply_blur_to_region(image, x_blur, y_blur, height_blur, width_blur)143 region_blur = cv2.cvtColor(region_blur, cv2.COLOR_BGR2RGB)144 return region_blur145 146 elif selected_function == 'Sharpen Image':147 sharpened_image = sharpen_image(image)148 sharpened_image = cv2.cvtColor(sharpened_image, cv2.COLOR_BGR2RGB)149 return sharpened_image150 151 elif selected_function == 'Thresholding':152 return apply_simple_thresholding(image)153 154 elif selected_function == 'Adaptive Thresholding':155 return apply_adaptive_thresholding(image)156 157 elif selected_function == 'Rotate Image':158 rotated_image = rotate_image(image, angle)159 rotated_image = cv2.cvtColor(rotated_image, cv2.COLOR_BGR2RGB)160 return rotated_image161 162 elif selected_function == 'Detect Borders':163 canny = detect_borders_canny(image)164 return canny165 166 elif selected_function == 'Segment Image':167 return segment_image(image)168 169 else:170 return None171 172# Show/Hide color channel dropdown based on selected function173def update_color_channel_interface(selected_function):174 return gr.update(visible=(selected_function == 'Extract Color Channel'))175 176# Show/Hide crop coordinates based on selected function177def update_crop_inputs_interface(selected_function):178 return [gr.update(visible=(selected_function == 'Crop Image'))] * 4179 180# Show/Hide blur region coordinates based on selected function181def update_blur_region_inputs_interface(selected_function):182 return [gr.update(visible=(selected_function == 'Blur a Region'))] * 4183 184# Show/Hide rotate angle input based on selected function185def update_rotate_angle_interface(selected_function):186 return gr.update(visible=(selected_function == 'Rotate Image'))187 188with gr.Blocks() as interface:189 # Dropdown for image processing functions190 function = gr.Dropdown(choices=['Display Image', 'Extract Color Channel', 'Grayscale Conversion', 'Crop Image', 'Blur', 'Blur a Region', 'Sharpen Image', 'Thresholding', 'Adaptive Thresholding', 'Rotate Image', 'Detect Borders', 'Segment Image'], label="Select Function")191 192 # Dropdown for selecting color channel (initially hidden)193 color_channel = gr.Dropdown(choices=['Blue', 'Green', 'Red'], label="Select Color Channel", visible=False)194 195 # Inputs for cropping coordinates (initially hidden)196 x_input_crop = gr.Number(label="X Coordinate (Crop)", visible=False)197 y_input_crop = gr.Number(label="Y Coordinate (Crop)", visible=False)198 width_input_crop = gr.Number(label="Width (Crop)", visible=False)199 height_input_crop = gr.Number(label="Height (Crop)", visible=False)200 201 # Inputs for blur region coordinates (initially hidden)202 x_input_blur = gr.Number(label="X Coordinate (Blur)", visible=False)203 y_input_blur = gr.Number(label="Y Coordinate (Blur)", visible=False)204 width_input_blur = gr.Number(label="Width (Blur)", visible=False)205 height_input_blur = gr.Number(label="Height (Blur)", visible=False)206 207 # Input for rotation angle (initially hidden)208 rotate_angle_input = gr.Number(label="Rotation Angle", visible=False)209 210 # File input211 image_input = gr.File(file_count="single", file_types=["image"], label="Upload Image")212 213 # Image output214 image_output = gr.Image(type="numpy", label="Processed Image")215 216 # Update visibility of color channel dropdown217 function.change(fn=update_color_channel_interface, inputs=function, outputs=color_channel)218 219 # Update visibility of crop inputs (x, y, width, height)220 function.change(fn=update_crop_inputs_interface, inputs=function, outputs=[x_input_crop, y_input_crop, width_input_crop, height_input_crop])221 222 # Update visibility of blur region inputs (x, y, width, height)223 function.change(fn=update_blur_region_inputs_interface, inputs=function, outputs=[x_input_blur, y_input_blur, width_input_blur, height_input_blur])224 225 # Update visibility of rotate angle input226 function.change(fn=update_rotate_angle_interface, inputs=function, outputs=rotate_angle_input)227 228 # Main image processing function229 submit_btn = gr.Button("Process Image")230 submit_btn.click(fn=process_image, inputs=[function, image_input, color_channel, x_input_crop, y_input_crop, width_input_crop, height_input_crop, rotate_angle_input, x_input_blur, y_input_blur, height_input_blur, width_input_blur], outputs=image_output)231 232interface.launch(share=True, debug=True)