numpy 如何将OpenCV图像(BGR和BGRA)转换为pygame.Surface对象?

ndasle7k  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(177)

我从OpenCV/opencv-pythonnumpy.array)创建了图像,我想将它们转换为pygame.Surface对象:

def cvImageToSurface(cv2Image):

    pygameSurface = # ? create from "cvImage"

    return pygameSurface 

surface = cvImageToSurface(cv2Image)

字符串
有些图像有三个通道(BGR),有些图像还有一个Alpha通道(BGRA)。在cvImageToSurface中,我需要做什么才能将其中一种格式的图像转换为pygame.Surface对象?

gorkyyrv

gorkyyrv1#

numpy.arrayshape属性是每个维度中的元素数。第一个元素是高度,第二个元素是宽度,第三个元素是通道的数量。可以通过pygame.image.frombuffer生成pygame.Surface。第一个参数可以是numpy.array,第二个参数的格式为(RGBRGBA)。
通过切片获取pygame.Surface对象的大小(widthheight):

size = cvImage.shape[1::-1]

字符串
根据第三个通道确定pygame.Surface对象的目标格式:

format = 'RGBA' if cvImage.shape[2] == 4 else 'RGB'


由于源格式为 BGRBGRA,但目标格式为 RGBRGBA,因此必须交换红色和蓝色通道:

cvImage[:, :, [0, 2]] = cvImage[:, :, [2, 0]]


在灰度图像的情况下,必须使用numpy.reshape更改阵列的形状,并且必须使用numpy.repeat将灰色通道扩展为红绿蓝颜色通道:

cvImage = np.repeat(cvImage.reshape(size[1], size[0], 1), 3, axis = 2)


利用他的数据,pygame.Surface对象可以由pygame.image.frombuffer生成:

surface = pygame.image.frombuffer(cvImage.flatten(), size, format)


为确保图像具有与显示器 Surface 相同的像素格式并获得最佳性能,Surface 应转换为convertconvert_alpha

surface = surface.convert_alpha() if format == 'RGBA' else surface.convert()


完整功能cvImageToSurface

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


最小示例:


的数据

import os
import pygame
import cv2 as cv
import numpy as np

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

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

cvImage1 = cv.imread('woodtiles.jpg', cv.IMREAD_GRAYSCALE)
cvImage2 = cv.imread('woodtiles.jpg', cv.IMREAD_UNCHANGED)
cvImage3 = cv.imread('Apple1-256.png', cv.IMREAD_UNCHANGED)
pygameSurface1 = cvImageToSurface(cvImage1)
pygameSurface2 = cvImageToSurface(cvImage2)
pygameSurface3 = cvImageToSurface(cvImage3)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill(0)
    window.blit(pygameSurface1, pygameSurface1.get_rect(topleft = window.get_rect().inflate(-10, -10).topleft))
    window.blit(pygameSurface2, pygameSurface2.get_rect(center = window.get_rect().center))
    window.blit(pygameSurface3, pygameSurface3.get_rect(bottomright = window.get_rect().inflate(-10, -10).bottomright))
    pygame.display.flip()

pygame.quit()

相关问题