提交 2a1be96a 编写于 作者: W wizardforcel

upgrade quant mode

上级 8d53062b
......@@ -4,7 +4,7 @@
## 安装
通过pip(推荐):
通过 pip(推荐):
```
pip install imgyaso
......@@ -16,7 +16,7 @@ pip install imgyaso
pip install git+https://github.com/apachecn/imgyaso
```
并且安装 [ImageMagick](https://imagemagick.org/script/download.php)[pngquant](https://pngquant.org/)
并且安装 [ImageMagick](https://imagemagick.org/script/download.php)
## 使用说明
......@@ -28,7 +28,7 @@ imgyaso [-h] [-v] [-c COLORS] [-m {grid,noise,trunc,quant,thres}]
-c COLORS: 颜色数,只对 trunc, quant 模式有效
-m MODE: 模式名称,值为 grid(灰度网格仿色),noise(灰度扩散仿色),
trunc(灰度截断),quant(颜色缩减),thres(自适应二值化),
默认为 grid
默认为 quant
-o OFNAME: 输出文件名称,默认和输入文件相同
fname: 输入文件名称
```
......
......@@ -8,7 +8,7 @@ from .quant import pngquant_bts
from .trunc import trunc_bts
from .util import *
modes = ['grid', 'noise', 'trunc', 'quant', 'thres']
modes = ['quant', 'grid', 'noise', 'trunc', 'thres']
is_img = lambda s: re.search(r'\.(jpg|jpeg|gif|png|bmp|webp|tiff)$', s)
......
import subprocess as subp
import tempfile
import uuid
import os
from os import path
import sys
import cv2
import libimagequant as liq
from PIL import Image
from io import BytesIO
from .util import *
def pngquant(img, ncolors=8):
......@@ -13,22 +12,31 @@ def pngquant(img, ncolors=8):
def pngquant_bts(img, ncolors=8):
img = conv2png(img)
fname = path.join(
tempfile.gettempdir(),
uuid.uuid4().hex + '.png'
)
with open(fname, 'wb') as f:
f.write(img)
subp.Popen(
['pngquant', str(ncolors), fname, '-o', fname, '-f'],
stdout=subp.PIPE,
stderr=subp.PIPE,
).communicate()
with open(fname, 'rb') as f:
img = f.read()
os.unlink(fname)
return img
img = Image.open(BytesIO(img)).convert('RGBA')
w, h = img.width, img.height
bytes = img.tobytes()
attr = liq.Attr()
attr.max_colors = ncolors
img = attr.create_rgba(bytes, w, h, 0)
res = img.quantize(attr)
res.dithering_level = 1.0
bytes = res.remap_image(img)
palette = res.get_palette()
img = Image.frombytes('P', (w, h), bytes)
palette_data = []
for color in palette:
palette_data.append(color.r)
palette_data.append(color.g)
palette_data.append(color.b)
img.putpalette(palette_data)
bio = BytesIO()
img.save(bio, 'PNG', optimize=True)
return bio.getvalue()
def main():
fname = sys.argv[1]
img = open(fname, 'rb').read()
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册