在 pygame 中临时保存图像 [英] Temporary save Image in pygame

查看:164
本文介绍了在 pygame 中临时保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个使用 pygame 作为界面和 opencv 进行图像处理的图像裁剪器.我已经创建了像crop()、colorfilter()等函数,但我将图像加载为pygame.image.load()以在屏幕上显示它但是当我执行crop()时它是numpy.ndarray并且pygame无法加载它得到错误:

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:

参数 1 必须是 pygame.Surface,而不是 numpy.ndarray

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

我该如何解决这个问题.我需要 blit() 裁剪后的图像.应该保存图像并阅读它,然后在完成后将其删除,因为我想应用多个过滤器.

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.

推荐答案

下面的函数将一个 OpenCV (cv2) 图像分别转换为一个 numpy.array(相同)到 pygame.Surface:

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()

如何将 OpenCV (cv2) 图像(BGR 和 BGRA)转换为 pygame.Surface 对象 以获取该函数的详细说明.

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

这篇关于在 pygame 中临时保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆