OpenCV : 'rect' expects four integers

Quick fix for OpenCV Python binding error when using rectangle structures. Explains why tuples must be used instead of lists for CvRect arguments and provides a simple code example.

OpenCV : 'rect' expects four integers
Photo by Artturi Jalli / Unsplash

You may encounter this error when using OpenCV with Python bindings, while trying to use the rectangle structure.

Here is an example :

!/usr/bin/env python
import cv
img = cv.LoadImage("test.jpg")
dims = cv.GetSize(img)
roi = [0, 0, dims[0] / 2, dims[1] / 2 ]
cv.SetImageROI(img, roi)

You will get this result:

Traceback (most recent call last):
File "newfile.py", line 8, in
cv.SetImageROI(img, roi)
TypeError: CvRect argument 'rect' expects four integers

The answer is pretty simple, you have to set rect as a tuple and not a list:

roi = (0, 0, dims[0] / 2, dims[1] / 2 )

There it is, pretty easy, isn't?!

I still lost 15 minuts searching for it yesterday ^^, won't do it twice :D

A small warning however, the values of the tuple can't be changed once initialized !

See ya