1

I am making an image cropper using pygame as interface and opencv for image processing. I have created function like crop(), colorfilter() etc but i load image as pygame.image.load() to show it on screen but when i perform crop() it is numpy.ndarray and pygame cannot load it getting error:

argument 1 must be pygame.Surface, not numpy.ndarray

how do i solve this problem. i need to blit() the cropped image. should save image and read it then delete it after its done as i want to apply more than one filters.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    See [How do I convert an OpenCV (cv2) image (BGR and BGRA) to a pygame.Surface object](https://stackoverflow.com/questions/64183409/how-do-i-convert-an-opencv-cv2-image-bgr-and-bgra-to-a-pygame-surface-object) – Rabbid76 Oct 18 '20 at 07:02

1 Answers1

2

The following function converts a OpenCV (cv2) image respectively a numpy.array (that's the same) to a pygame.Surface:

import numpy as np
def cv2ImageToSurface(cv2Image):
    if cv2Image.dtype.name == 'uint16':
        cv2Image = (cv2Image / 256).astype('uint8')
    size = cv2Image.shape[1::-1]
    if len(cv2Image.shape) == 2:
        cv2Image = np.repeat(cv2Image.reshape(size[1], size[0], 1), 3, axis = 2)
        format = 'RGB'
    else:
        format = 'RGBA' if cv2Image.shape[2] == 4 else 'RGB'
        cv2Image[:, :, [0, 2]] = cv2Image[:, :, [2, 0]]
    surface = pygame.image.frombuffer(cv2Image.flatten(), size, format)
    return surface.convert_alpha() if format == 'RGBA' else surface.convert()

See How do I convert an OpenCV (cv2) image (BGR and BGRA) to a pygame.Surface object for a detailed explanation of the function.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Thanks for the answer this really solved my problem easily. – Creeper2962 Oct 18 '20 at 08:07
  • 1
    @Creeper2962 Thank you. You've welcome. I hope the explanation ([link](https://stackoverflow.com/questions/64183409/how-do-i-convert-an-opencv-cv2-image-bgr-and-bgra-to-a-pygame-surface-object)) helped you understand how it works. – Rabbid76 Oct 18 '20 at 08:11
  • just one question how do i convert black and white image as it has shape(x,y) and your solution gives "out of range" error . – Creeper2962 Oct 18 '20 at 08:38
  • 1
    @Creeper2962 I'll investigate this and en extend the answer. Just one moment... – Rabbid76 Oct 18 '20 at 08:40
  • I have used cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) to convert it to gray image and its shape is (x,y) not (x,y,1) sorry for my typo. – Creeper2962 Oct 18 '20 at 08:44
  • @Creeper2962 I've improved the function and I've extended the explanation in answer to the other question: [How do I convert an OpenCV (cv2) image (BGR and BGRA) to a pygame.Surface object](https://stackoverflow.com/questions/64183409/how-do-i-convert-an-opencv-cv2-image-bgr-and-bgra-to-a-pygame-surface-object) – Rabbid76 Oct 18 '20 at 09:00