简体   繁体   English

在pygame中临时保存图像

[英]Temporary save Image in pygame

I am making an image cropper using pygame as interface and opencv for image processing.我正在制作一个使用 pygame 作为界面和 opencv 进行图像处理的图像裁剪器。 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:我创建了像crop()、colorfilter()等函数,但我将图像加载为pygame.image.load()以在屏幕上显示它但是当我执行crop()时它是numpy.ndarray并且pygame无法加载它得到错误:

argument 1 must be pygame.Surface, not numpy.ndarray参数 1 必须是 pygame.Surface,而不是 numpy.ndarray

how do i solve this problem.我该如何解决这个问题。 i need to blit() the cropped image.我需要 blit() 裁剪后的图像。 should save image and read it then delete it after its done as i want to apply more than one filters.应该保存图像并阅读它,然后在完成后将其删除,因为我想应用多个过滤器。

The following function converts a OpenCV (cv2) image respectively a numpy.array (that's the same) to a pygame.Surface :以下函数将 OpenCV (cv2) 图像分别从numpy.array (相同)转换为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.有关该函数的详细说明,请参阅如何将 OpenCV (cv2) 图像(BGR 和 BGRA)转换为 pygame.Surface 对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM