Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Drawing a rectangle around the red color region

Hi. I am trying to draw a rectangle around the biggest red color region in the image. image description

import cv2
import numpy as np

img = cv2.imread("ther.jpg")
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


mask1 = cv2.inRange(img_hsv, (0,90,50), (5,255,255))
mask2 = cv2.inRange(img_hsv, (175,90,50), (180,255,255))

## Merge the mask and crop the red regions
mask = cv2.bitwise_or(mask1, mask2 )



(_,contours,_) = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    area = cv2.contourArea(c)
    print(area)
    if(area>800):
        x,y,w,h = cv2.boundingRect(c)
        frame = cv2.rectangle(img,(x,y),(x+w,x+h),(0,0,255),5)
        cv2.imshow(" ",frame)

When I run this code, it doesn't work. Can anyone help me with this? I'm running out of ideas. Many thanks in advance.

Drawing a rectangle around the red color region

Hi. I am trying to draw a rectangle around the biggest red color region in the image. image description

import cv2
import numpy as np

img = cv2.imread("ther.jpg")
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


mask1 = cv2.inRange(img_hsv, (0,90,50), (5,255,255))
mask2 = cv2.inRange(img_hsv, (175,90,50), (180,255,255))

## Merge the mask and crop the red regions
 mask = cv2.bitwise_or(mask1, mask2 )



(_,contours,_) = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    area = cv2.contourArea(c)
    print(area)
    if(area>800):
        x,y,w,h = cv2.boundingRect(c)
        frame = cv2.rectangle(img,(x,y),(x+w,x+h),(0,0,255),5)
        cv2.imshow(" ",frame)

When I run this code, it doesn't work. Can anyone help me with this? I'm running out of ideas. Many thanks in advance.