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

前端 未结 3 1692
日久生厌
日久生厌 2021-01-15 01:19

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

相关标签:
3条回答
  • 2021-01-15 01:35

    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)
    
    0 讨论(0)
  • 2021-01-15 01:43

    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')
    
    0 讨论(0)
  • 2021-01-15 01:46

    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)
    
    0 讨论(0)
提交回复
热议问题