Showing posts with label opencv. Show all posts
Showing posts with label opencv. Show all posts

Saturday, May 11, 2024

Evolving from Edge Detection to Object Detection: Exploring Color Identification

 In the realm of computer vision, the journey from edge detection to object detection is an exciting evolution, marking significant progress in image processing and machine learning. Today, we'll explore this journey as we enhance a simple edge detection program to identify objects and discern their colors.

Sample Output:




Note that the detected object was enclosed in a rectangle with dimensions extended 10 pixels beyond the outermost detected pixels around the contour. And also note that the program assumes that the object has no other contours identified inside of it and it has solid and uniformly distributed color, hire me for more complex images.

 If you want to save the detected object from the image assuming that there are several objects detected in the original image, you can use the following code:

# Crop the region of interest (ROI)
    roi = image[y:y+h, x:x+w]

    # Save the cropped image
    cv2.imwrite("cropped_image.jpg", roi)

Edge Detection: The Starting Point

We begin our journey(see previous post "Edge Detection with Python and OpenCV: A Simple Guide") with a classic edge detection program. Using OpenCV, we load an image and apply the Canny edge detection algorithm. This process extracts edges from the image, highlighting the boundaries between different objects.

Progression to Object Detection

As we inspect our edge detection program, we notice its potential to evolve into an object detection tool. By identifying contours and drawing bounding boxes around objects, we take a step closer to this transformation.

Introducing Color Identification

To enrich our program, we integrate color identification. Utilizing the average color within the bounding box, we determine the predominant color of each detected object and display it alongside its RGB values.

Conclusion: Towards Image Classification

Our journey from edge detection to object detection, supplemented by color identification, illustrates the iterative nature of computer vision development. As we refine our techniques, we inch closer to the ultimate goal: enabling machines to perceive and understand visual information, laying the groundwork for advanced tasks like image classification and or optical character recognition(OCR) in machine learning.

Cheers to the endless possibilities that lie ahead in the realm of computer vision and artificial intelligence!

Here is the code:

import cv2
import numpy as np

# Load the image
image = cv2.imread("ball.jpg")

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply edge detection
edges = cv2.Canny(gray, 100, 200)  # You can adjust the thresholds as needed

# Find contours
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Iterate through detected contours
for contour in contours:
    # Get the bounding box of the contour
    x, y, w, h = cv2.boundingRect(contour)
    # Identify the color of the object
    roi = image[y:y+h, x:x+w]
    roi_rgb = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
    mask = np.all(roi_rgb == [255, 2255, 255], axis=-1)
    mask = ~mask
    roi_without_color = roi_rgb[mask]
    avg_color = np.average(roi_without_color, axis=0)
    print(roi_without_color)
    
    color = tuple(np.round(avg_color).astype(int))

    # Enlarge the rectangle by 10 pixels
    x -= 10
    y -= 10
    w += 20
    h += 20
    
    # Draw a rectangle around the contour
    cv2.rectangle(image, (x, y), (x + w, y + h), (128, 64, 0), 1)
    
    
    
    # Display the color name and RGB values
    color_name = ('RGB: ' + str(color[0]) + ', '  +  str(color[1])+ ', '  + str(color[2]))
    
    
    cv2.putText(image, f"{color_name}", (x+5, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (128, 0, 0), 2)
    # Draw the detected edges in blue color with thickness 1
    cv2.drawContours(image, contours, -1, (255, 0, 0), 1)
# Display the result
cv2.imshow("Detected Objects", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Friday, May 10, 2024

Edge Detection with Python and OpenCV: A Simple Guide

 Introduction:

In the world of computer vision and image processing, edge detection is a fundamental technique used to identify boundaries within images. Whether it's for object detection, image segmentation, or feature extraction, accurate edge detection is crucial. In this blog post, we'll explore how to perform edge detection using Python and OpenCV, a powerful library for computer vision tasks.

What is Edge Detection?

Edge detection is the process of identifying the boundaries of objects within an image. These boundaries, known as edges, are regions where significant changes in intensity or color occur. Edge detection algorithms aim to highlight these areas, making them stand out from the rest of the image. These edges can then be used for various purposes, such as object recognition, image segmentation, and more.

How Canny Edge Detection Works:

Canny edge detection involves several steps:

  1. Smoothing: Before detecting edges, the image is smoothed to reduce noise. This is typically done using a Gaussian filter to blur the image slightly.

  2. Gradient Calculation: The intensity gradients of the image are calculated using derivative filters, such as the Sobel operator, in both the horizontal and vertical directions. These gradients represent the rate of change of intensity at each pixel.

  3. Non-maximum Suppression: This step aims to thin the edges by removing pixels that are not part of the strongest edges. It involves examining each pixel and suppressing it if it is not a local maximum along the direction of the gradient.

  4. Edge Thinning by Hysteresis: Canny edge detection uses two threshold values: a lower threshold (weak edge pixels) and an upper threshold (strong edge pixels). Pixels with gradient magnitudes above the upper threshold are considered strong edge pixels, while those between the two thresholds are considered weak edge pixels. Weak edge pixels are only considered part of the edge if they are connected to strong edge pixels. This helps in reducing noise and preserving continuous edges.

Advantages of Canny Edge Detection:

  1. Accurate Detection: Canny edge detection is known for its accuracy in detecting edges while minimizing false positives.

  2. Low Error Rate: By utilizing non-maximum suppression and hysteresis thresholding, Canny edge detection reduces the chances of detecting spurious edges.

  3. Parameter Tuning: The algorithm allows for easy adjustment of parameters such as the thresholds for controlling the sensitivity of edge detection.

  4. Good Performance: Despite being computationally intensive, Canny edge detection performs well in various conditions and is suitable for real-time applications.

Getting Started:

To perform edge detection in Python, we'll use OpenCV, a popular open-source library for computer vision tasks. OpenCV provides a variety of functions and algorithms for image processing, including edge detection. Let's dive into a simple example of edge detection using Python and OpenCV.

Sample Input Image:


Result:



import cv2
import numpy as np

# Load the image
image = cv2.imread("google.jpg", cv2.IMREAD_GRAYSCALE)

# Apply edge detection with increased tolerance
edges = cv2.Canny(image, 100, 300)  # Adjust the thresholds as needed for better edge detection

# Find contours
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Create a blank canvas with the same dimensions as the input image
blank_canvas = np.zeros_like(image)

# Draw the contours on the blank canvas
contour_image = cv2.drawContours(blank_canvas, contours, -1, (255), 1)

# Display the result
cv2.imshow("Detected Edges", contour_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

In this code:

  • We load an image using OpenCV's cv2.imread() function and convert it to grayscale.
  • We apply the Canny edge detection algorithm using cv2.Canny(). The parameters 100 and 300 represent the lower and upper thresholds respectively. Adjust these thresholds as needed for better edge detection.
  • We find contours using cv2.findContours(). Contours are the outlines of objects within an image.
  • We create a blank canvas using NumPy's np.zeros_like() function with the same dimensions as the input image.
  • We draw the contours on the blank canvas using cv2.drawContours().
  • Finally, we display the resulting image using cv2.imshow().

Conclusion:

Edge detection is a fundamental technique in computer vision and image processing. With Python and OpenCV, performing edge detection is both simple and powerful. By leveraging OpenCV's functions and algorithms, we can identify boundaries within images and extract valuable information for various applications. Experiment with different parameters and techniques to achieve optimal results for your specific use case. Happy coding!

Sunday, January 7, 2024

Moving Image Regions with Python, Tkinter and OpenCV

 Overview

Imagine having a tool that allows you to interactively delete specific regions of an image with just a few clicks. This Python and Tkinter application empowers users to open an image, draw rectangles around unwanted regions, and seamlessly delete or relocate them. This technical documentation provides an insight into the functionality of each method, shedding light on how this program achieves its remarkable image manipulation capabilities.



Feature Highlights

Open Image: The application starts by prompting the user to open an image file. The selected image is loaded using OpenCV, ensuring compatibility with various image formats.


Draw Rectangles: Users can draw rectangles on the image canvas by clicking and dragging. These rectangles define the regions to be manipulated.


Move and Delete: The application introduces an innovative approach to both moving and deleting image regions. When the user holds the Shift key and clicks, the selected region becomes interactive, allowing effortless relocation. Additionally, the program enables the deletion of unwanted regions, providing a dynamic and user-friendly experience.


Method Breakdown

open_image

This method is responsible for opening a file dialog, allowing users to select an image file. Once an image is selected, it is loaded using OpenCV, and the display_image method is called to present it on the Tkinter canvas.


display_image

The display_image method converts the image from BGR to RGB format and creates a Tkinter PhotoImage object. This image is then displayed on the canvas, ensuring correct dimensions and preventing garbage collection.


select_rect

This method is triggered when the user holds the Shift key and clicks, activating the cursor for moving rectangles or images. It adds the 'selected' tag to the current canvas item.


activate_cursor

The activate_cursor method sets the cursor in motion, binding it to the movement of rectangles or images. When the user releases the mouse button, the deselect method is called.


deselect

The deselect method removes the 'selected' tag, deactivating the cursor. It rebinds the canvas to the initial event handlers, allowing the user to draw rectangles or select regions.


move_rect

The move_rect method handles the movement of rectangles or images. If a rectangle is selected, it is moved using the coords method. If an image is selected, the program calculates the displacement and moves the canvas item accordingly.


on_button_press, on_move_press, on_button_release

These methods respond to mouse events. on_button_press initializes the drawing of rectangles, on_move_press captures the drawn region, and on_button_release finalizes the process.


Conclusion

In essence, this Python and Tkinter application serves as an interactive image manipulation tool, allowing users to draw, move, and delete specific regions effortlessly. By leveraging OpenCV and Tkinter, it provides a robust platform for customizing and extending image processing projects. Whether you're a developer exploring image manipulation or an enthusiast seeking a powerful yet accessible tool, this program opens the door to a world of possibilities.

The source code can be downloaded at my patreon shop.