Python - 将位图图像转换为每像素颜色列表

2024-06-26 01:54:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能代码的位图高达22×22像素,但任何比这更奇怪的事情发生,有人知道为什么吗? 该程序将用于在minecraft/可能的其他基于像素的游戏中自动构建大型结构。目前的状态是工作到22x22像素,但没有更多,我想知道为什么/如何修复它。在

当前错误消息(对于大于22像素的图像): KeyError(搜索调色板时,原因:颜色不再是rgb的元组,而是未知原因的单个数字

所需大小为128 x 128,结果是(对于2 x 1位图)-简化为可能必须是正方形: [(0,0,'0-0-0',黑色),(0,1,'255,255,255',白色)]

当前课程:

# palette.py
# Palette with rgb-values depicting different blocks in-game:
predef = {}         #initialize a list variable, the fill it:
predef['255-255-255'] = 'air'
predef['255---0---0'] = 'redstone_block'
predef['--0--38-255'] = 'lapis_block'
predef['0-0-0'] = 'coal_block'

# main.py
from PIL import Image
import numpy as np
import json
import palette

def convert(filein, pal = palette.predef, zz = 0):
    '''
    due to a combined internal/external palette system ignore the warnings about incoherent types of str and dict
    as the dict is the internal, and the str is the filename of a json containing a dict.

    :param filein: Filename of bitmap
    :param pal: blank to use internal, or specify a separate palette.json
    :return:
    '''
    customset = []                  # customset list for blocks and positions

    if pal is not palette.predef:
        with open(pal) as js:
            pal = json.load(js)
        #print(pal) #debug to check palette

    im = Image.open(str(filein))
    p = np.array(im) #.reshape(-1, 3)
    print('width/height:', len(p), 'by', len(p))
    for y in range(0, len(p)):
        for x in range(0, len(p)):
            pix = p[y][x]
            pix = str(pix).replace(' ', '-').replace('[', '').replace(']', '')
            print(pix)
            pixcolor = (y, x, pix, pal[pix])     # Switch comment statu on these to see the error
            #pixcolor = pix                      # instead of the error message

            customset.append(pixcolor)

    return customset

print(convert('./1.bmp', './palettetest.json') # works with a bitmap up to 22 by 22

Tags: ofthetoimportjsonlenwith像素
1条回答
网友
1楼 · 发布于 2024-06-26 01:54:00

找到了解决方案:

从PIL导入图像 将numpy作为np导入 导入json 导入时间 导入调色板#为什么我们在上面有0-0-0时需要这个选项??-未知

def convert(filein, pal = palette.predef, zz = 0):
    '''
    due to a combined internal/external palette system ignore the warnings about incoherent types of str and dict
    as the dict is the internal, and the str is the filename of a json containing a dict.

    :param filein: Filename of bitmap
    :param pal: blank to use internal, or specify a separate palette.json
    :return:
    '''
    customset = []                  # customset list for blocks and positions
    if pal is not palette.predef:
        with open(pal) as js:
            pal = json.load(js)
        #print(pal)

    photo = Image.open(filein)  # opens the image
    photo = photo.convert('RGB')

    width = photo.size[0]
    height = photo.size[1]
    print('Size of current image is: {} by {}\n'.format(width, height))
    for y in range(0, height):
        row = ''

        for x in range(0, width):
            RGB = photo.getpixel((x,y))     # Gets the color value of pixel in color rgb
            R, G, B = RGB                   # Splits the rgb values
            rgb= str(RGB).replace(', ','-').replace('(', '').replace(')', '')
            info = 'x: {}, y: {} - pixelcolor: {}, block: {}'.format(x, y, rgb, pal[rgb])
            time.sleep(0.01) # to releave the cpu a bit
            customset.append(info)
            #print(info)

    return customset

print(convert('./1.bmp'))

相关问题 更多 >