将图片按灰度转换成字符

文章描述了一个Python程序,用于读取BMP图像文件(如1.bmp),通过特定计算方法(calc函数)将RGB值转换为字符(ch数组),然后写入新的文本文件(res.txt)。程序展示了如何逐像素处理BMP文件并进行编码。
摘要由CSDN通过智能技术生成

 

from struct import *

ch = ['.', ':', '!', '~', '+','=', '^', '*','$', '#']//可以在这里面由浅到深添加字符
ch.reverse()

def calc(R, G, B):#模式L
    return R * 299 // 1000 + G * 587 // 1000 + B * 144 / 1000


def character( val):
    num = val / 260 * len(ch)
    num = round(num)
    if num>=len(ch):
        num=len(ch)-1
    return ch[num]

class rmb:
    def __init__(self, path):
        file = open(path, 'rb')

        self.bfType = file.read(2)
        self.bfSize = file.read(4)
        self.bfReserved1 = file.read(2)
        self.bfReserved2 = file.read(2)
        self.bfOffBits = file.read(4)

        self.biSize = file.read(4)
        self.biWidth = file.read(4)
        self.biHeight = file.read(4)
        self.biPlanes = file.read(2)
        self.biBitCount = file.read(2)

        self.biCompression = file.read(4)
        self.biSizeImage = file.read(4)
        self.biXPelsPerMeter = file.read(4)
        self.biYPelsPerMeter = file.read(4)
        self.biClrUsed = file.read(4)
        self.biClrImportant = file.read(4)
        self.bmp_data = []

        self.h, = unpack("<i", self.biHeight)
        self.w, = unpack("<i", self.biWidth)
        print(self.h)
        print(self.w)

        for height in range(self.h):
            bmp_data_row = []
            count = 0
            for width in range(self.w):
                bmp_data_row.append(
                    [unpack("<B", file.read(1))[0], unpack("<B", file.read(1))[0], unpack("<B", file.read(1))[0]])
                count += 3

            while count % 4 != 0:
                file.read(1)
                count += 1
            self.bmp_data.append(bmp_data_row)
        self.bmp_data.reverse()
        file.close()

    def write_(self):
        res_file = open('res.txt', 'w')

        for height in range(self.h):
            bmp_data_row = self.bmp_data[height]
            for width in range(self.w):
                R = bmp_data_row[width][0]
                G = bmp_data_row[width][1]
                B = bmp_data_row[width][2]
                res_file.write(character(calc(R,G,B)))
            res_file.write('\n')


res = rmb('1.bmp')#图片路径bmp格式
res.write_()

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值