首页 > 解决方案 > 如何从图像中获取 RGB 颜色代码并使它们成为数组?

问题描述

在提出问题之前,我想展示我用于读取 Excel 单元格的 Python 代码,在该单元格中我正在绘制我想要的任何内容,并为 arduino 代码准备 Excel 单元格以在 32x92pixel 塔上点亮。

    import xlrd
    ExcelFileName= 'data.xlsx'
    workbook = xlrd.open_workbook(ExcelFileName) 
    worksheet = workbook.sheet_by_name("Sheet1")
#inside of the data.xlsx file I create 39 row and 31 column and this where I'm #drawing what I want to light up.

    num_rows = worksheet.nrows #Number of Rows
    num_cols = worksheet.ncols #Number of Columns

    x=0  #for x line
    y=0  #for y line
    floors=-1
    rooms=-1

    def cell(y,x):  #for getting values from each cells

        return worksheet.cell_value(y, x) # Read the data in the current cell

    #this is tower model and every floor has 92 addressable rgb leds.And there is 30 floors.Each 10 floor has different data cable so 1 data line controls 920 rgb.

    #On arduino I have macro which is "#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR*92))" this.So if I write floor and room number I will get number of led.Because all strip connect to each other.
    #First floor data connected from "right bottom corner",this is my start point for leds.And I'm reading excel cells so I have to start to reading from right bottom corner to have in order for my leds.

    for i in range(30,20,-1):
        y=i
        floors+=1
        for j in range(38,0,-1):
            x=j
            rooms+=1
            if rooms>37:
                rooms=0
            print("leds[LEDNO(" + str(floors) + "," + str(rooms) +")].setRGB(" + str(cell(y,x)) + ");")

    #for next 10 floor rooms should start from -1 again.
    rooms=-1
    for i in range(20,10,-1):

        y=i
        floors+=1
        for j in range(38,0,-1):
            x=j
            rooms+=1
            if rooms>37:
                rooms=0
            print("leds2[LEDNO(" + str(floors) + "," + str(rooms) +")].setRGB(" + str(cell(y,x)) + ");")

    rooms=-1
    for i in range(10,0,-1):
        y=i
        floors+=1
        for j in range(38,0,-1):
            x=j
            rooms+=1
            if rooms>37:
                rooms=0
            print("leds3[LEDNO(" + str(floors) + "," + str(rooms) +")].setRGB(" + str(cell(y,x)) + ");")

问题:如何使用 Python 从图像中获取 RGB 代码?是否可以将此 RGB 代码转换为 30x92 像素?至少我需要读取和打印给定的图像像素。

我需要从图像中获取 RGB 颜色代码,就像我在 excel 上所做的一样。我不知道它是否可以使用 Python。

标签: pythonarduino

解决方案


您可能希望使用 scipy 将图像读取为 (30,92,3) numpy 数组(最后一个可能为 ,4,具体取决于您未显示的文件),然后根据需要分配值:

img[i, j, :] = RGBvalue

推荐阅读