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 t
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)
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')
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)