[英]How do I cut the black things out of an image in pygame?
嘿,我想剪掉圖像的黑色部分,以便只留下沒有黑色的圖像,然后程序應保存新圖像,但是我不知道該怎么做:/我只是知道如何顯示圖片:
import pygame
import os
pygame.init()
surface = pygame.display.set_mode((500,500))
asurf = pygame.image.load(os.path.join("shot.png"))
asurf = pygame.transform.scale(asurf, (500, 500))
surface.blit(asurf,(0,0))
pygame.display.flip()
編輯:對不起,我的最初答案僅與PyGame中的透明度有關,而不與保存圖像有關。
要進行像素修改,您可能需要使用另一個庫,例如PIL(Python Imaging Library)。
如果您想試一下PIL,請參見此主題: PIL替換顏色的最佳方法?
如果您想堅持使用PyGame,則應該查看pygame.surfarray: http ://www.pygame.org/docs/tut/surfarray/SurfarrayIntro.html
EDIT2:這是一個簡短的代碼段:
import pygame
# initialize pygame
pygame.init()
pygame.display.set_mode((500, 500))
# load image
image_surf = pygame.image.load('test.png',).convert_alpha()
# load pixel information from surface
image_pixels = pygame.surfarray.pixels3d(image_surf)
# create a copy for pixel manipulation
new_surf = image_surf.copy()
# loop through every pixel
i = 0
for x in range(len(image_pixels)):
for y in range(len(image_pixels[0])):
if image_pixels[x][y][0] == 0 and image_pixels[x][y][1] == 0 and image_pixels[x][y][2] == 0:
# set transparency
new_surf.set_at((x, y), pygame.Color(0, 0, 0, 0))
# save image
pygame.image.save(new_surf, "out.png")
老答案:如何在PyGame中實現透明度
您需要查找set_colorkey(): http ://www.pygame.org/docs/ref/surface.html#pygame.Surface.set_colorkey
如果您的圖像已經是透明的,則只需使用.convert_alpha()加載圖像:
asurf = pygame.image.load(os.path.join("shot.png")).convert_alpha()
即使您的圖像沒有透明度,調用.convert()也是一個好主意:
asurf = pygame.image.load(os.path.join("shot.png")).convert()
請參閱以下內容:(由於僅2個鏈接的限制,鏈接已刪除)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.