10

I know all the solutions on the internet say to give integer co-ordinates but that isn't working for me.

def box(x,y,w,h):
    print(x,y,w,h)
    print(type(x),type(y),type(w),type(h))
    cv2.rectangle(image, (int(x),int(y)) , (int(x+w),int(y+h)) , (255,0,0) , 2.0) ----> error

for i in indices.flatten():
    x,y,w,h = boxes[i][0],boxes[i][1],boxes[i][2],boxes[i][3]
    box(int(x),int(y),int(w),int(h))    

Output of debug

414 1308 53 404
<class 'int'> <class 'int'> <class 'int'> <class 'int'>

Python version - 3.7.0 OpenCv version - 4.4.0.42

Yash Khasgiwala
  • 500
  • 1
  • 4
  • 16
  • 3
    `thickness`, your last parameter, must be `int` type, cf. the [`rectangle` doc](https://docs.opencv.org/4.4.0/d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9). – HansHirse Sep 04 '20 at 08:33
  • 1
    hi, did you get the answer? I am also facing same issue. – Mayank Kumar Chaudhari Jan 27 '21 at 15:37
  • 1
    This happens if the passed coordinates are other than `int` – mrtpk Aug 25 '21 at 15:01
  • In my case large negative values (-2147483646, -2147483657) for pt1 and pt2 (2nd and 3rd inputs) caused the same error message. Not very clear message... – Antti A Sep 19 '21 at 18:23

2 Answers2

12

Using int coordinates worked well for me.

(startX, startY, endX, endY) = rect
startX = int(startX * W)
startY = int(startY * H)
endX = int(endX * W)
endY = int(endY * H)

cv2.rectangle(frame, (startX, startY), (endX, endY), (155, 255, 0), 2)

above code worked well. In my case rect contained values from 0 to 1.

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
3

TypeError: function takes exactly 4 arguments (2 given) happens if any coordinate is not int.

Consider below snippets:

arr = np.zeros([200, 100, 3], np.int8)
_ = cv2.rectangle(arr, (-100, 20), (0, 0), (255, 0, 0), 2)

The above snippet will work. But the following snippets will raise TypeError:

_ = cv2.rectangle(arr, (-100, 20), (0, 0.0), (255, 0, 0), 2)

_ = cv2.rectangle(arr, (-100, 20), (0, 12345678900000000000000001), (255, 0, 0), 2)
mrtpk
  • 1,398
  • 4
  • 18
  • 38