Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13981

OpenCV: Drawing Squares Only in Free Spaces Within Vanning Slots

$
0
0

I'm working on an image processing project using OpenCV in Python where I need to identify free spaces within vanning slots and draw squares only in those free areas.

However, I'm encountering some difficulties in achieving this. Here's a brief overview of what I'm trying to accomplish and the problem I'm facing:

Objective:I have an image of warehouse vanning slots where the slots are delineated by yellow lines. My goal is to identify the free spaces within each slot and draw green squares only in those free areas.

Current Approach:I've implemented a Python code that calculates the free areas within each vanning slot.

Then, I attempt to draw green squares in the free areas based on the grid points generated within the convex hull of the free area contours.

Issue:The code runs without errors, but it seems that the squares are not accurately drawn in the free spaces. It appears that the squares are being drawn in areas where the Pallets Occupied area, rather than in the actual free spaces.

Code:

import osimport cv2import numpy as npfrom PIL import Imagefrom IPython.display import display# Function to generate grid points within the convex hulldef generate_grid_points(hull, square_size):    min_x, min_y, max_x, max_y = hull[:, 0, 0].min(), hull[:, 0, 1].min(), hull[:, 0, 0].max(), hull[:, 0, 1].max()    grid_points = []    for y in range(min_y, max_y, square_size):        for x in range(min_x, max_x, square_size):            if cv2.pointPolygonTest(hull, (x, y), False) >= 0:                grid_points.append((x, y))    return grid_points# Function to draw squaresdef draw_squares(image, grid_points, square_size):    for point in grid_points:        start_x, start_y = point        end_x = start_x + square_size        end_y = start_y + square_size        cv2.rectangle(image, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)# Function to calculate the number of squares in each slotdef calculate_square_count_in_slot(grid_points, square_size):    return len(grid_points)# Function to add vanning slot numbers and square countsdef add_slot_info(image, contour, slot_number, square_count, square_size):    x, y, w, h = cv2.boundingRect(contour)    color = (0, 0, 255) if slot_number % 2 == 1 else (204, 0, 204)  # Red for odd slots, pink for even slots    cv2.putText(image, f"Vanning Slot : {slot_number} ({square_count} sq)", (x, y + h + 55), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 0, 0), 4)    cv2.rectangle(image, (x, y), (x + w, y + h), color, 10)# Get Path to current working directorycwd = os.getcwd()# Load the imageimage_path = os.path.join(cwd, "C:/Users/Santhosh Kumar/OneDrive/Desktop/vanning_area/half_vanning - Copy - Copy.jpg")# Check if file existsif not os.path.isfile(image_path):    print("File", image_path, "doesn't exist")    exit()image = cv2.imread(image_path)# Convert the image to grayscalegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Apply a Gaussian blur with a 5x5 kernel to reduce noisegray = cv2.GaussianBlur(gray, (5, 5), 0)# Define the lower and upper bounds for the yellow color in HSVlower_yellow = np.array([20, 100, 100], dtype=np.uint8)upper_yellow = np.array([40, 255, 255], dtype=np.uint8)# Convert the image to HSV color spacehsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)# Create a binary mask for the yellow coloryellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)# Apply a bitwise AND operation to extract the gray area covered by yellow linesgray_area = cv2.bitwise_and(gray, gray, mask=yellow_mask)# Find the contours of the gray area with modified hierarchy parametercontours, hierarchy = cv2.findContours(gray_area, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# Define a max area size to filter out small contoursminAreaSizeAllowed = 400  # quite sensitive# Square size for gridsquare_size = 10  # Adjust this value based on your requirement# Initialize slot numberslot_number = 1# Process each contour independentlyfor contour in contours:    # Filter the contours by area    if cv2.contourArea(contour) > minAreaSizeAllowed:        # Calculate convex hull of the contour        hull = cv2.convexHull(contour)        # Generate grid points within the convex hull        grid_points = generate_grid_points(hull, square_size)        # Draw squares        draw_squares(image, grid_points, square_size)        # Calculate the square count in each slot        square_count = calculate_square_count_in_slot(grid_points, square_size)        # Add vanning slot numbers and square counts        add_slot_info(image, contour, slot_number, square_count, square_size)        # Increment slot number        slot_number += 1# Save the resultoutput_path = os.path.join(cwd, 'C:/Users/Santhosh Kumar/OneDrive/Desktop/vanning_area/output2.jpg')  # Change this to the desired output pathcv2.imwrite(output_path, image)print("Result image saved to:", output_path)# Open the image fileimg = Image.open(output_path)# Display the imagedisplay(img)

Viewing all articles
Browse latest Browse all 13981

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>