1

I ran into an error. I need to track motion in a specific area of a video. But when I try to crop a frame using ROI or a rectangle, Python throws the following error:

Traceback (most recent call last): File "C:\Users\Nitro 5\Desktop\sad.py", line 22, in diff = cv2.absdiff(frame1, frame2) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\core\src\arithm.cpp:650: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'cv::arithm_op'

I'm still a beginner, I tried to find something similar on the Internet, but nothing happened:( Can someone help me?

My code:

import cv2 
import imutils

cap = cv2.VideoCapture(0); 

#cap.set(3,1280)
#cap.set(4,700)

ret, frame1 = cap.read()
ret, frame2 = cap.read()

r = cv2.selectROI(frame1)
frame1 = frame1[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]

frame2 = frame2[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]



while cap.isOpened(): 


  diff = cv2.absdiff(frame1, frame2) 

  gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) 

  blur = cv2.GaussianBlur(gray, (5, 5), 0) 

  _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) 

  dilated = cv2.dilate(thresh, None, iterations = 3) 

  сontours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 

  for contour in сontours:
    (x, y, w, h) = cv2.boundingRect(contour)

    if cv2.contourArea(contour) < 1000:
      continue
    cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2) 
    cv2.putText(frame1, "Status: {}".format("Dvijenie is detected!"), (10, 20),     cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3, cv2.LINE_AA)
    print('Motion Detection. Object area  - ',     cv2.contourArea(contour))
     
  cv2.imshow("WebCamera", frame1)
  frame1 = frame2  #
  ret, frame2 = cap.read()   

  if cv2.waitKey(1) == 27: 
    break


cap.release()
cv2.destroyAllWindows()
Mikhail
  • 11
  • 2
  • 1
    what are the shapes of frame1 and frame2? why do you fail to check `ret`? `if not ret: break` -- you need to work with official tutorials and documentation. anything you find on the internet (youtube) is going to be ***bad*** because it doesn't teach you how to use these APIs properly – Christoph Rackwitz Jun 28 '22 at 18:25
  • 2
    Why are you placing everything before cv2.read().? That is not a practical way to write. – toyota Supra Jun 28 '22 at 20:35
  • The problem arises mainly due to different shapes/sizes of frame1 and frame2. please ensure their size is same before calling `cv2.absdiff(frame1, frame2)` – Prashant Maurya Jun 29 '22 at 08:27

0 Answers0