利用Python实现:将图片转化为Excel并保存

# -*- coding: utf-8 -*-

"""
@author:  yangsong
@file:    ImgToCsv.py
@time:    2019-3-14 11:56
@desc:    
@version: 1.0
"""

from PIL import Image
import numpy as np
import time
import matplotlib.pyplot as plt
import xlsxwriter


def get_xy(row, col):
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    num1 = col / 26
    num2 = col % 26

    if int(num1) == 0:
        return table[num2 - 1] + str(row)
    else:
        return table[int(num1) - 1] + table[num2 - 1] + str(row)

def main():
    img = np.array(Image.open('1.jpg'))

    # plt.figure(figsize=(100, 100))
    # plt.imshow(img)
    # plt.show()
    rows, cols, dims = img.shape
    print(img.shape)
    print(img.dtype)
    print(img.size)
    print(type(img))
    # plt.imshow(img)
    # plt.show()
    # print img[188, 188, 0]

    excel = xlsxwriter.Workbook('1.xlsx')

    cellformat = excel.add_format({'bg_color': '#123456',
                                'font_color': '#654321'})
    worksheet1 = excel.add_worksheet()
    data = []
    color = [''] * cols
    cellcolor = ""
    for i in range(rows):
        for j in range(cols):
            cellcolor = (hex(img[i, j, 0]) + hex(img[i, j, 1]) + hex(img[i, j, 2])).replace('0x', '')
            cellformat = excel.add_format({'bg_color': '#'+cellcolor,
                                  'font_color': '#'+cellcolor})

            worksheet1.conditional_format(get_xy(i, j), {'type': 'cell',
                                                        'criteria': '<',
                                                        'value': 50,
                                                        'format': cellformat})

    excel.close()

if __name__ == '__main__':
    main()


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值