Thursday, December 3, 2015

Object Detection using opencv

def Story():
     
           Well it has been few months since I updated the blog. Well now I have been given an opportunity to work on FPGAs from the start of my 3rd semester. I started learning image processing in my first year and I am still growing on...

int main()

This is my first tutorial towards image processing. This tutorial will help you identify basic objects which can be further tracked or processed. First of you will require opencv python installed. Before that you have to install numpy depending on your processor.Lets get started !!!.

The opencv python windows installation procedure can be found in this link;Opencv Windows installation

The below image shows a red object being detected. This is a basic program to which helps us to get started with opencv.



I hope the code is self explanatory with its comments.
Happy coding!!..
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import cv2
import numpy as np
cap = cv2.VideoCapture(0) #Start Video Capture
while True:
 ret,frame=cap.read() #Capture a frame
 img=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)  #Convert BGR to HSV for easy processing
 lo=np.array([160,100,100])     # lower and upper Threshold values for inRange. The object of
 up=np.array([179,255,255])     # my intrest is red color.
 mask=cv2.inRange(img,lo,up,None)     # It only shows pixels in the given color range
 kernel=np.ones((5,5),np.uint8)  # A small matrix used for processing by morph function
 mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel) # Morph is used to remove the noise
 _,cnt,hie=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) # It identifies the objects in our image
 for i in range(len(cnt)):
  moments = cv2.moments(cnt[i]) # It gives a dictionary of all moment values. Here we use it for calculating centre
  x,y,w,h=cv2.boundingRect(cnt[i]) # Find a rectangle bounding our contour
  if w*h>5000:     # If area is greater than this then it is considered as a object.(optional)
   cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) # Draw the rectangle with the specified points
   cv2.circle(frame,(int(moments['m10']/moments['m00']), int(moments['m01']/moments['m00'])),2,(0,255,0),3)
   # Draw the centre of the rectangle
 cv2.imshow("frame",frame) # Display the frames
 cv2.imshow("mask",mask)
 k=cv2.waitKey(60) & 0xff # The program exits if ESC key is pressed
 if k==27:
  break

cap.release()
cv2.destroyAllWindows()
#IIE

No comments:

Post a Comment