4

Following the object detection process with the Opencv library in the following code array, I give the output information as an argument to matplotlib. But the video process comes slowly. If I only do object detection and not run the graph section; real-time object detection is doing very well. But when you do both together, the object detection process slows down. Do you have any suggestions for speeding up the process?

pixel_number_row = []
while True:
   ret, frame = cap.read()

   if ret == True :     
      hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
      y , x = hsv.shape[:2] #x = 320 , y = 240

      # Define 'brown' range in HSV colorspace
      lower = np.array([10, 100, 20])
      upper = np.array([20, 255, 200])

      # Threshold the HSV image to get only brown color
      mask1 = cv2.inRange(hsv, lower, upper)
      kernel = np.ones((5,5),np.uint8)
      thresh = cv2.dilate(mask1,kernel,iterations = 2)

      # find contours in thresholded image, then grab the largest
      # one
      cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
      cnts = imutils.grab_contours(cnts)
      c = max(cnts, key=cv2.contourArea)

      # determine the most extreme points along the contour
      extLeft  = tuple(c[c[:, :, 0].argmin()][0])
      extRight = tuple(c[c[:, :, 0].argmax()][0])
      extTop   = tuple(c[c[:, :, 1].argmin()][0])
      extBot   = tuple(c[c[:, :, 1].argmax()][0])

      cv2.drawContours(thresh, [c], -1, (0, 255, 255), 2)
      cv2.circle(thresh, extLeft , 8, (0, 0, 255)  , -1)
      cv2.circle(thresh, extRight, 8, (0, 255, 0)  , -1)
      cv2.circle(thresh, extTop  , 8, (255, 0, 0)  , -1)
      cv2.circle(thresh, extBot  , 8, (255, 255, 0), -1)

      x_center = (extLeft[0] + extRight[0] + extTop[0] + extBot[0])/4
      y_center = (extLeft[1] + extRight[1] + extTop[1] + extBot[1])/4

      cv2.circle(frame,(x_center, y_center), 3, (0,255,0), -1)

      cv2.line(frame,(extLeft[0] ,0),(extLeft[0],y) ,(0,255,0),2)             # y axis - binary 
      cv2.line(frame,(extRight[0],0),(extRight[0],y),(0,255,0),2)                 # y axis - binary 
      cv2.line(frame,(0,extTop[1])  ,(x,extTop[1])  ,(0,255,0),2)                 # x axis - binary 
      cv2.line(frame,(0,extBot[1])  ,(x,extBot[1])  ,(0,255,0),2)                 # x axis - binary 

      pixel_number_row.append(x_center)


      plt.plot(pixel_number_row - pixel_number_row[0]) # plotting by columns
      plt.xlabel('frame number')
      plt.ylabel('x axis moving')
      # fig.canvas.draw()
      plt.pause(0.001)

      if (cnt % 60 == 0):
          pixel_number_row = []
          plt.clf()
         cnt += 1

      # show the output image
      # cv2.imshow("mask" , thresh)
      cv2.imshow("Image", frame)
  k = cv2.waitKey(1)
  if k == 27:
      break


print(end - start)
plt.show()
cv2.destroyAllWindows()
nathancy
  • 42,661
  • 14
  • 115
  • 137

0 Answers0