日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python将图像转换为8位单通道_使用Python将图片转换为单通道黑白图片

發布時間:2023/12/1 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python将图像转换为8位单通道_使用Python将图片转换为单通道黑白图片 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文介紹如何使用python將圖片轉換為純黑白的單通道圖片。文中用到的腳本支持彩色、灰度、帶alpha通道的輸入圖片以及SVG矢量圖,支持調整輸出圖片大小以及設置灰度閾值。

最后介紹如何輸出SSD1306 OLED顯示屏可用的XBM文件,并利用輸出的XBM數據在0.96寸的OLED屏幕上顯示圖標,例如下圖中的溫度、鬧鐘及云朵圖標通過本腳本生成:

使用方法

通過pip安裝依賴包:pip3 install --user pillow argparse numpy cairosvg

從下文拷貝python腳本為tobw.py.

要把非單通道圖片(如彩色、灰度或帶alpha通道的PNG圖片)轉換圖片 只需指定輸入圖片路徑和輸除路徑即可:$ python tobw.py -i input.png -o output_bw.jpg

通過-h選項查看其他可選參數:$ python tobw.py -h

usage: tobw.py [-h] -i INPUT_IMAGE -o OUTPUT_IMAGE [-t THRESHOLD] [-r] [-s SIZE] [-p]

optional arguments:

-h, --help show this help message and exit

-i INPUT_IMAGE, --input-image INPUT_IMAGE

Input image

-o OUTPUT_IMAGE, --output-image OUTPUT_IMAGE

output image

-t THRESHOLD, --threshold THRESHOLD

(Optional) Threshold value, a number between 0 and 255

-r, --invert-bw (Optional) Invert black and white

-s SIZE, --size SIZE (Optional) Resize image to the specified size, eg., 16x16

-p, --print (Optional) Print result

-s 縮放圖片

使用-s選項設置輸出圖片的大小,不設置時,輸出與輸入大小相同。例如把輸出圖片設置微16X16像素大小:python3 tobw.py -i input.png -o output_bw.jpg -s 16x16需要注意如果輸出圖片長寬比與輸入圖片長寬比不一致,圖片會被拉伸或壓縮。

-t 調整閾值

使用-t選項設置輸出為黑或白像素點的灰度閾值,取值范圍為0-255. 值越小就有更多像素點被設置為白色。如果輸出圖片丟失的細節過多時,可以適當調整本參數。

反轉輸出的黑白像素

使用-r參數后,原來輸出白色的像素點將顯示微黑色,反之亦然。輸入圖片的明暗區域恰好與顯示屏相反時可以使用本參數。

在ESP8266 Arduino里使用

使用esp8266-oled-ssd1306庫提供的drawXbm(x, y, img_width, img_height, img)方法在屏幕上繪制圖片,drawXbm的5個參數分別是x, y: 圖片的坐標,屏幕左上角坐標為(0, 0) 。此處設置的坐標對應圖片左上角位置。

img_width: 圖片的實際寬度。

img_height: 圖片的實際高度。

img: XBM圖片字節,使用tobw.py的-p參數獲取。

esp8266-oled-ssd1306使用XBM格式圖片,使用tobw.py的-p參數獲取,例如下面的示例把svg圖片轉換為12x12像素輸出,并打印XBM格式數據。注意返回的im_bits,這就是drawXbm最后一個參數需要的數據。$ python3 tobw.py -i rain.svg -o rain_bw.jpg -s 12x12 -t 200 -p

111000001111

110001000111

110011100011

100111110001

001111111100

011111111110

001100000100

000000000000

100000000001

111000001111

111100111111

111100111111

Result as XBM image:

#define im_width 12

#define im_height 12

static char im_bits[] = {

0x07,0x0f,0x23,0x0e,0x73,0x0c,0xf9,0x08,0xfc,0x03,0xfe,0x07,0x0c,0x02,0x00,

0x00,0x01,0x08,0x07,0x0f,0xcf,0x0f,0xcf,0x0f

};

源碼# Convert image to pure black and white

# Show usages:

# python tobw.py -h

# python tobw.py -i rain.svg -o rain_bw.jpg -s 12x12 -t 200

from PIL import Image, UnidentifiedImageError

import argparse

import numpy as np

from cairosvg import svg2png

import os

from random import random

ap = argparse.ArgumentParser()

ap.add_argument("-i", "--input-image", help="Input image", type=str, required=True)

ap.add_argument("-o", "--output-image", help="output image", type=str, required=True)

ap.add_argument("-t", "--threshold",

help="(Optional) Threshold value, a number between 0 and 255", type=int, default=128)

ap.add_argument("-r", "--invert-bw",

help="(Optional) Invert black and white", action='store_true')

ap.add_argument("-s", "--size", help="(Optional) Resize image to the specified size, eg., 16x16", type=str)

args = vars(ap.parse_args())

invert_bw = args['invert_bw']

threshold = args['threshold']

if threshold > 255 or threshold < 0:

raise Exception('Invalid threshold value!')

img_in = args['input_image']

img_out = args['output_image']

if args['size']:

size = [int(n) for n in args['size'].lower().split('x')]

else:

size = None

high = 255

low = 0

if invert_bw:

high = 0

low = 255

def replace_ext(filename, new_ext):

ext = filename.split('.')[-1] if '.' in filename else ''

return filename[:len(filename)-len(ext)] + str(new_ext)

def remove_transparency(im, bg_colour=(255, 255, 255)):

# https://stackoverflow.com/questions/35859140/remove-transparency-alpha-from-any-image-using-pil/35859141

# Only process if image has transparency (http://stackoverflow.com/a/1963146)

if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):

alpha = im.convert('RGBA').getchannel('A')

bg = Image.new("RGBA", im.size, bg_colour + (255,))

bg.paste(im, mask=alpha)

return bg

else:

return im

# color image

try:

col = Image.open(img_in)

except UnidentifiedImageError:

if (img_in.lower().endswith('.svg')):

tmp = replace_ext(img_in, '{}.png'.format(random()))

svg2png(url=img_in, write_to=tmp)

col = Image.open(tmp)

else:

raise Exception('unknown image type')

if size:

col = col.resize(size)

col = remove_transparency(col)

gray = col.convert('L')

bw = gray.point(lambda x: low if x < threshold else high, '1')

bw.save(img_out)

for u8 in np.uint8(bw):

print(''.join(str(c) for c in u8))

print()

print('Result as XBM image:')

if (img_out.lower().endswith('.xbm')):

print(open(img_out).read())

else:

xbm_out = replace_ext(img_in, '{}.xbm'.format(random()))

bw.save(xbm_out)

print(open(xbm_out).read())

os.remove(xbm_out)

if tmp is not None:

os.remove(tmp)

總結

以上是生活随笔為你收集整理的python将图像转换为8位单通道_使用Python将图片转换为单通道黑白图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。