获取Pygame中图像的单个像素的颜色

获取Pygame中图像的单个像素的颜色

本文介绍了获取Pygame中图像的单个像素的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取被涂在pygame表面上的图像像素的颜色值?使用Surface.get_at()仅返回表面层的颜色,而不返回已在其上发白的图像.

How can I get the colour values of pixels of an image that is blitted onto a pygame surface? Using Surface.get_at() only returns the color of the surface layer, not the image that has been blitted over it.

推荐答案

方法surface.get_at很好.这是一个示例,显示了在不使用Alpha通道的情况下对图像进行刮涂时的区别.

The method surface.get_at is fine.Here is an example showing the difference when blitting an image without alpha channel.

import sys, pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
image = pygame.image.load("./img.bmp")
image_rect = image.get_rect()

screen.fill((0,0,0))
screen.blit(image, image_rect)
screensurf = pygame.display.get_surface()

while 1:

  for event in pygame.event.get():
     if event.type == pygame.MOUSEBUTTONDOWN :
        mouse = pygame.mouse.get_pos()
        pxarray = pygame.PixelArray(screensurf)
        pixel = pygame.Color(pxarray[mouse[0],mouse[1]])
        print pixel
        print screensurf.get_at(mouse)

  pygame.display.flip()

在这里,点击红色像素将显示:

Here, clicking on a red pixel will give :

(0, 254, 0, 0)
(254, 0, 0, 255)

PixelArray返回0xAARRGGBB颜色分量,而Color预期为0xRRGGBBAA.另外请注意,屏幕表面的Alpha通道为255.

The PixelArray returns a 0xAARRGGBB color component, while Color expect 0xRRGGBBAA. Also notice that the alpha channel of the screen surface is 255.

这篇关于获取Pygame中图像的单个像素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:15