Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding framing algorithm/extracting a certain object of interest in Python

This is the image

Hello, for a personal project I need to crop out extract this underwater gate from an image, and leave out anything other than the gate. The image is colored here but I can assume that the image of the gate I receive will only be lined, with the gate being white lines and the background being black. Could anyone give me any advice about how to go about this solution? I'm a novice when it comes to OpenCV so I'm a bit lost.

like image 734
roozevelt23 Avatar asked Jan 22 '26 12:01

roozevelt23


1 Answers

Here's the main idea

  • Gaussian blur image and extract blue channel
  • Threshold image with cv2.threshold()
  • Erode to remove black lines and isolate gate with cv2.erode()
  • Find contours and filter for gate contour using cv2.findContours() and cv2.contourArea()
  • Create a mask and dilate image using cv2.dilate()
  • Crop gate using cv2.bitwise_and()
import cv2
import numpy as np

# Load in image and create copy
image = cv2.imread('1.png')
original = image.copy()

# Gaussian blur and extract blue channel
blur = cv2.GaussianBlur(image, (3,3), 0)
blue = blur[:,:,0]

# Threshold image and erode to isolate gate contour
thresh = cv2.threshold(blue,135, 255, cv2.THRESH_BINARY_INV)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
erode = cv2.erode(thresh, kernel, iterations=4)

# Create a mask and find contours
mask = np.zeros(original.shape, dtype=np.uint8)
cnts = cv2.findContours(erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

# Filter for gate contour using area and draw onto mask
for c in cnts:
    area = cv2.contourArea(c)
    if area > 6000:
        cv2.drawContours(mask, [c], -1, (255,255,255), 2)

# Dilate to restore contour and mask it with original image
dilate = cv2.dilate(mask, kernel, iterations=7)
result = cv2.bitwise_and(original, dilate)

cv2.imshow('thresh', thresh)
cv2.imshow('erode', erode)
cv2.imshow('mask', mask)
cv2.imshow('dilate', dilate)
cv2.imshow('result', result)
cv2.waitKey()
like image 178
nathancy Avatar answered Jan 24 '26 01:01

nathancy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!