Vivek Vaibhav Roy
Vivek Vaibhav Roy

Reputation: 59

Getting an "integer is required (got type tuple)" error, drawing a rectangle using cv2

I have written a basic Python code to create an image and then putting a rectangle on the boundaries. This doesn't seem to work. I have checked multiple sites and this is the exact code they use. Don't know what is the issue.

import cv2
import numpy as np
img = Image.new('RGB', (800, 900), color= (171, 183, 255))
cv2.rectangle(img,(1,1),(800,900),(255,0,0),15)
img

I am getting this error

TypeError
<ipython-input-251-4b78f75077e8> in <module>()
      4 img = Image.new('RGB', (800, 900), color= (171, 183, 255))
      5 # cv2.rectangle(img, 0, 0, 800, 900, (255,0,0))
----> 6 cv2.rectangle(img,(1,1),(800,900),(255,0,0),15)
      7 img

TypeError: an integer is required (got type tuple)

Can anyone please help?

Upvotes: 2

Views: 8515

Answers (3)

Sharky
Sharky

Reputation: 4543

In some cases OpenCV will need wrapping image with UMat class.

img = Image.new('RGB', (800, 900), color= (171, 183, 255))
open_cv_image = np.array(img) 
image = cv2.UMat(open_cv_image).get()
cv2.rectangle(open_cv_image,(0,0),(800,900),(0,0,0),30)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124858

The cv2 module works with numpy arrays as images, not with PIL Image instances.

Because both the cv2.rectangle implementation and the Image type are implemented entirely in compiled code, the traceback is not all that helpful in understanding what is going wrong. Under the hood, the native cv2.rectangle() code tries to access something on the image object that required an integer but cv2.rectangle() passed in a tuple instead, as it was expecting to be interacting with a numpy array.

If all you wanted was a blank image with uniform RGB colour, create a numpy array with shape (width, height, 3) and your 3 bands set to your preferred RGB value:

import numpy as np

# numpy equivalent of Image.new('RGB', (800, 900), color=(171, 183, 255))
img = np.zeros((800, 900, 3), np.uint8)
img[..., :] = (171, 183, 255)

then apply your cv2.rectangle() call to that array.

You can always convert from and to a PIL image with:

# create numpy array from PIL image
nparray = np.array(img)
# create PIL image from numpy array
img = Image.fromarray(nparray)

Upvotes: 4

Vivek Vaibhav Roy
Vivek Vaibhav Roy

Reputation: 59

Found the solution. Thanks @Martijn Pieters

import cv2
import numpy as np
from PIL import Image

img = Image.new('RGB', (800, 900), color= (171, 183, 255))
open_cv_image = np.array(img) 

cv2.rectangle(open_cv_image,(0,0),(800,900),(0,0,0),30)
img2 = Image.fromarray(open_cv_image, 'RGB')

Upvotes: 3

Related Questions