2

I have been trying to identify the contours of red colored objects in Open Cv (python 2.7) and we have succeeded in identifying them. But, I want to detect the position of the red colored object (left or right) and I have not succeeded in doing so. If anyone could give me the code or steps to do so, I would be really thankful.

Our current code for identifying red colored objects is as follows:

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(1):
  _, frame = cap.read()
  hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  lower_color = np.array([0, 50, 50])
  upper_color = np.array([60, 255, 255])
  mask = cv2.inRange(hsv, lower_color, upper_color)
  mask = cv2.erode(mask, None, iterations=2)
  mask = cv2.dilate(mask, None, iterations=2)
  res = cv2.bitwise_and(frame, frame, mask=mask)

  cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
  cv2.drawContours(frame, cnts, 0, (127, 255, 0), 3)
 print cnts
 cv2.imshow('frame', frame)
 cv2.imshow('mask', mask)
 cv2.imshow('res', res)
 cv2.imshow('contours', frame)



 k = cv2.waitKey(5) & 0xFF
 if k == 27:
    print "release"

    break
 cap.release()
 cv2.destroyAllWindows()

1 Answers1

1

Well, You are one step away of getting the position. You can create a boundingrect around the contour(s) and then you can calculate it's center to obtain the coordinates of the object.

You can also try minEnclosingCircle That will give you the center and the radius of it. This could be a little more direct to find the center :)

Here you can find a small tutorial of both functions, but in c++.

in python would be something like this

...  
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
cv2.drawContours(frame, cnts, 0, (127, 255, 0), 3)
(x,y),radius = cv2.minEnclosingCircle(cnts[0])
center = (int(x),int(y))
radius = int(radius)
cv2.circle(frame, center, radius, (255, 0, 0), 3)
...

in this case, center will be the position of your object. This code only takes in account the first contour in the array...

api55
  • 11,070
  • 4
  • 41
  • 57
  • cv2.circle(frame, center, radius, (255, 0, 0), 3) TypeError: integer argument expected, got float i got this error... could you please gide me on where I have to add the statements in my program.... This is really urgent as I am working on a project right now. – Adhityan Sridharan Apr 28 '16 at 12:06
  • @AdhityanSridharan What program for this? I already gave you the code to put inside your own code.... I updated the code to fix the error – api55 Apr 28 '16 at 12:14