Good day. I can not understand what the error is. Launched for the first time - everything started, the second time - no longer. What could be a mistake? PS I will say right away that in this I recently, previously only sat on Java. The error can be elementary)

Code:

import cv2 import numpy as np from PIL import ImageGrab kernelOpen=np.ones((5,5)) kernelClose=np.ones((20,20)) while(True): #Get current window frames = np.array(ImageGrab.grab(bbox =(0,40,1280,720))) #Convert window to RGB format framess = cv2.cvtColor(frames, cv2.COLOR_BGR2RGB) frame = cv2.GaussianBlur(framess, (17, 17), 0) #Convert window to HSV format hsvs = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) hsv= cv2.GaussianBlur(hsvs, (17, 17), 0) lower_red = np.array([20, 100, 100]) upper_red = np.array([30, 255, 255]) mask = cv2.inRange(hsv, lower_red, upper_red) maskOpen=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernelOpen) maskClose=cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose) maskFinal=maskClose im, conts, h = cv2.findContours(maskFinal.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) center =None c=max(conts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) cv2.putText(frame,"Distance", (center[0]+10,center[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.4,(0, 0, 255),1) cv2.putText(frame,"("+str(center[0])+","+str(center[1])+")", (center[0]+10,center[1]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.4,(0, 0, 255),1) cv2.drawContours(hsv,conts,-1,(255,0,0),3) for i in range(len(conts)): x,y,w,h=cv2.boundingRect(conts[i]) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255), 2) res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('original', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() 

Mistake:

 Traceback (most recent call last): File "C:\Users\Andrey\Desktop\test123.py", line 28, in <module> c = max(conts, key=cv2.contourArea) ValueError: max() arg is an empty sequence 
  • Maybe throw a mistake? - MrBin
  • Yes ... I forgot. Added error - CrazyProgrammist pm
  • 2
    Everything is logical, conts is empty. So the contour is not found. Most likely so. - MrBin
  • one
    To create large applications, use debuggers. It's easier, even though it is an easy and readable language. - MrBin
  • @MrBin, btw judging by the text of the error, even the debugger is not needed, everything is written and where and why :) - Anton Komyshan

1 answer 1

Once written is an empty sequence , then conts empty:

 Traceback (most recent call last): File "C:\Users\Andrey\Desktop\test123.py", line 28, in <module> c = max(conts, key=cv2.contourArea) ValueError: max() arg is an empty sequence 

I think print(conts) will give []

To prevent the error from adding a check, for example:

 while True: ... im, conts, h = cv2.findContours(maskFinal.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if not conts: print('Not found contours') continue ...