write openCV code that will detect an image of a pond and draw a differently coloured…
- User
write openCV code that will detect an image of a pond and draw a differently coloured rectangle around each fish detected
- Assistant
write openCV code that will detect an image of a pond and draw a differently coloured rectangle around each fish detected
Certainly! Detecting fish in a pond image and drawing differently colored rectangles around each detected fish can be accomplished using OpenCV in Python. Below is a step-by-step guide along with sample code to help you achieve this.
Python installed on your system.
OpenCV library installed. You can install it using pip:
pip install opencv-python
import cv2
import numpy as np
import random
def detect_fish_and_draw_rectangles(image_path, output_path):
# Load the image
image = cv2.imread(image_path)
if image is None:
print("Error: Image not found or unable to read.")
return
# Resize the image for easier processing (optional)
scale_percent = 60 # percent of original size
width = int(image.shape[1] * scale_percent / 100)
height = int(image.shape[0] * scale_percent / 100)
image = cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian Blur to reduce noise and improve edge detection
blurred = cv2.GaussianBlur(gray, (7, 7), 0)
# Edge detection using Canny
edges = cv2.Canny(blurred, 50, 150)
# Dilate and erode to close gaps between edges
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
edges = cv2.dilate(edges, kernel, iterations=2)
edges = cv2.erode(edges, kernel, iterations=1)
# Find contours in the edged image
contours, hierarchy = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Initialize a list to hold bounding rectangles of detected fish
fish_bounding_rects = []
# Loop over the contours to filter out potential fish
for cnt in contours:
# Calculate contour area and ignore small areas
area = cv2.contourArea(cnt)
if area < 500: # Adjust this threshold based on image size and fish size
continue
# Approximate the contour to reduce the number of points
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
# Use bounding rectangle
x, y, w, h = cv2.boundingRect(approx)
# Aspect ratio and other heuristics can be added here to filter fish
aspect_ratio = w / float(h)
if 0.5 < aspect_ratio < 2.0: # Adjust based on fish shape
fish_bounding_rects.append((x, y, w, h))
# Draw rectangles with random colors
for rect in fish_bounding_rects:
x, y, w, h = rect
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
# Save and display the output image
cv2.imwrite(output_path, image)
cv2.imshow("Detected Fish", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
input_image_path = "pond.jpg" # Replace with your input image path
output_image_path = "pond_with_fish_detected.jpg" # Output image path
detect_fish_and_draw_rectangles(input_image_path, output_image_path)
Loading and Resizing the Image:
cv2.imread. Ensure that the path to your pond image is correct.Preprocessing:
Edge Detection:
Finding and Filtering Contours:
Drawing Rectangles:
Saving and Displaying the Image:
Advanced Detection:
Color Segmentation:
Morphological Operations:
Parameter Tuning:
If your fish have distinctive colors, using color segmentation can enhance detection. Here's an additional method using color thresholds in HSV space.
# Convert to HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Define color range for the fish (this needs to be adjusted based on actual fish color)
lower_color = np.array([25, 40, 40])
upper_color = np.array([75, 255,255])
# Create a mask for the fish color
mask = cv2.inRange(hsv, lower_color, upper_color)
# Perform morphological operations
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=1)
# Find contours on the mask
contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Proceed with the same contour filtering and rectangle drawing as above
The provided code offers a basic method for detecting fish in a pond image using OpenCV's classical image processing techniques. Depending on the complexity of your images and the variability of fish appearances, you may need to refine the preprocessing steps, adjust thresholds, or employ more sophisticated machine learning approaches for optimal results.
Feel free to customize the code to better fit the specific characteristics of your pond images and the fish you intend to detect.
Not yet included in a published release.