Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Code for answer to question on Stackoverflow:
- # "opencv - find a red line in image by python cv2 - Stack Overflow"
- # https://stackoverflow.com/questions/77037396/find-a-red-line-in-image-by-python-cv2
- import cv2
- class RedLineDetector:
- def __init__(self):
- self.image = None
- def load_image(self, image_path):
- self.image = cv2.imread(image_path)
- def detect_line(self):
- if self.image is None:
- raise ValueError("No image loaded. Please load an image using 'load_image' method.")
- height, width, _ = self.image.shape
- print(height, width)
- min_width = 300 # Minimum width of the red line
- min_height = 10 # Minimum height of the red line
- max_height = 50 # Maximum height of the red line
- ### I reduce size to see full image on screen ###
- preview_image = cv2.resize(self.image, (width//4, height//4))
- cv2.imshow('image', preview_image)
- #cv2.waitKey(0)
- # find red pixels in some range
- thresh = cv2.inRange(self.image, (50,50,160), (120, 120, 200))
- #print(thresh)
- ### I reduce size to see full image on screen ###
- preview_thresh = cv2.resize(thresh, (width//4, height//4))
- cv2.imshow('thresh', preview_thresh)
- #cv2.waitKey(0)
- # find contours with red pixels
- contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- contours = contours[0] if len(contours) == 2 else contours[1]
- print('len(contours)', len(contours))
- #print(contours)
- result = self.image.copy()
- bounding_box = None
- for c in contours:
- #area = cv2.contourArea(c)
- x, y, w, h = cv2.boundingRect(c)
- if min_width < w and min_height < h < max_height:
- bounding_box = x, y, w, h
- cv2.drawContours(result, [c], -1, (0, 255, 0), 2)
- print('w, h:', w, h)
- break
- ### I reduce size to see full image on screen ###
- preview_result = cv2.resize(result, (width//4, height//4))
- cv2.imshow('result', preview_result)
- cv2.waitKey(0)
- return bounding_box
- # Example usage
- detector = RedLineDetector()
- detector.load_image('frame3.jpg')
- bounding_box = detector.detect_line()
- if bounding_box is not None:
- print("Bounding Box Coordinates:", bounding_box)
- else:
- print("No red line detected.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement