提交 ab815541 编写于 作者: W wizardforcel

init

上级
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
The Star And Thank Author License (SATA)
Copyright © 2019 ApacheCN(apachecn@163.com)
Project Url: https://github.com/apachecn/imgyaso
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
And wait, the most important, you shall star/+1/like the project(s) in project url
section above first, and then thank the author(s) in Copyright section.
Here are some suggested ways:
- Email the authors a thank-you letter, and make friends with him/her/them.
- Report bugs or issues.
- Tell friends what a wonderful project this is.
- And, sure, you can just express thanks in your mind without telling the world.
Contributors of this project by forking have the option to add his/her name and
forked project url at copyright and project url sections, but shall not delete
or modify anything else in these two sections.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# ImgYaso
(施工中)
\ No newline at end of file
#! /bin/sh
rm -rf BiliDriveEx.egg-info
rm -rf build
rm -rf dist
\ No newline at end of file
# -*- coding: utf-8 -*-
"""ImgYaso
https://github.com/apachecn/imgyaso"""
__author__ = "ApacheCN"
__email__ = "apachecn@163.com"
__license__ = "SATA"
__version__ = "2020.04.28"
import argparse
from os import path
from . import __version__
from .adathres import adathres_bts
from .dither import grid_bts, noise_bts
from .quant import pngquant
from .trunc import trunc_bts
from .util import *
modes = ['grid', 'noise', 'trunc', 'quant', 'thres']
def main():
parser = argparse.ArgumentParser(description='ImgYaso')
parser.add_argument('fname', help='file name to be processed')
parser.add_argument('-c', '--colors', type=int, default=8, help='num of colors')
parser.add_argument('-m', '--mode', default=modes[0], choices=modes, help='processing mode')
parser.add_argument('-o', '--ofname', help='output file name')
args = parser.parse_args()
if not path.exists(args.fname):
print('file not found')
return
with open(args.fname, 'rb') as f:
img = f.read()
img = conv2png(img)
if args.mode == 'grid':
img = grid_bts(img)
elif args.mode == 'noise':
img = noise_bts(img)
elif args.mode == 'trunc':
img = trunc_bts(img, args.colors)
elif args.mode == 'quant':
img = pngquant(img, args.colors)
elif args.mode == 'thres':
img = adathres_bts(img)
fname = args.ofname or args.fname
with open(fname, 'wb') as f:
f.write(img)
print('done...')
if __name__ == '__main__': main()
\ No newline at end of file
import numpy as np
from scipy import signal
import cv2
import re
import os
from os import path
import sys
def adathres_bts(img, win=9, beta=0.9):
img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_GRAYSCALE)
img = adathres(img, win, beta).astype(np.uint8)
img = bytes(cv2.imencode('.png', img, [cv2.IMWRITE_PNG_BILEVEL, 1])[1])
return img
def adathres(img, win=9, beta=0.9):
if win % 2 == 0: win = win - 1
# 边界的均值有点麻烦
# 这里分别计算和和邻居数再相除
kern = np.ones([win, win])
sums = signal.correlate2d(img, kern, 'same')
cnts = signal.correlate2d(np.ones_like(img), kern, 'same')
means = sums // cnts
# 如果直接采用均值作为阈值,背景会变花
# 但是相邻背景颜色相差不大
# 所以乘个系数把它们过滤掉
img = np.where(img < means * beta, 0, 255)
return img
def main():
fname = sys.argv[1]
img = open(fname, 'rb').read()
img = adathres_bts(img)
with open(fname, 'wb') as f:
f.write(img)
if __name__ == '__main__': main()
\ No newline at end of file
# coding: utf-8
# 四色网格仿色
import sys
import cv2
import numpy as np
pts = [
[0, 0], # 1/16
[2, 2],
[0, 2],
[2, 0],
[1, 1],
[3, 3],
[3, 1],
[1, 3],
[2, 3],
[0, 1],
[0, 3],
[2, 1],
[1, 0],
[3, 2],
[1, 2],
[3, 1], # 16/16
]
settings = [
{'fc': 0, 'bc': 0, 'k': 0}, # b
{'fc': 85, 'bc': 0, 'k': 1},
{'fc': 85, 'bc': 0, 'k': 2},
{'fc': 85, 'bc': 0, 'k': 3},
{'fc': 85, 'bc': 0, 'k': 4},
{'fc': 85, 'bc': 0, 'k': 5},
{'fc': 85, 'bc': 0, 'k': 6},
{'fc': 85, 'bc': 0, 'k': 7},
{'fc': 85, 'bc': 0, 'k': 8},
{'fc': 85, 'bc': 0, 'k': 9},
{'fc': 85, 'bc': 0, 'k': 10},
{'fc': 85, 'bc': 0, 'k': 11},
{'fc': 85, 'bc': 0, 'k': 12},
{'fc': 85, 'bc': 0, 'k': 13},
{'fc': 85, 'bc': 0, 'k': 14},
{'fc': 85, 'bc': 0, 'k': 15},
{'fc': 0, 'bc': 85, 'k': 0}, # c1
{'fc': 85, 'bc': 170, 'k': 15},
{'fc': 85, 'bc': 170, 'k': 14},
{'fc': 85, 'bc': 170, 'k': 13},
{'fc': 85, 'bc': 170, 'k': 12},
{'fc': 85, 'bc': 170, 'k': 11},
{'fc': 85, 'bc': 170, 'k': 10},
{'fc': 85, 'bc': 170, 'k': 9},
{'fc': 85, 'bc': 170, 'k': 8},
{'fc': 85, 'bc': 170, 'k': 7},
{'fc': 85, 'bc': 170, 'k': 6},
{'fc': 85, 'bc': 170, 'k': 5},
{'fc': 85, 'bc': 170, 'k': 4},
{'fc': 85, 'bc': 170, 'k': 3},
{'fc': 85, 'bc': 170, 'k': 2},
{'fc': 85, 'bc': 170, 'k': 1},
{'fc': 0, 'bc': 170, 'k': 0}, # c2
{'fc': 255, 'bc': 170, 'k': 1},
{'fc': 255, 'bc': 170, 'k': 2},
{'fc': 255, 'bc': 170, 'k': 3},
{'fc': 255, 'bc': 170, 'k': 4},
{'fc': 255, 'bc': 170, 'k': 5},
{'fc': 255, 'bc': 170, 'k': 6},
{'fc': 255, 'bc': 170, 'k': 7},
{'fc': 255, 'bc': 170, 'k': 8},
{'fc': 255, 'bc': 170, 'k': 9},
{'fc': 255, 'bc': 170, 'k': 10},
{'fc': 255, 'bc': 170, 'k': 11},
{'fc': 255, 'bc': 170, 'k': 12},
{'fc': 255, 'bc': 170, 'k': 13},
{'fc': 255, 'bc': 170, 'k': 14},
{'fc': 255, 'bc': 170, 'k': 15},
{'fc': 0, 'bc': 255, 'k': 0}, # w
]
def make_noise(size, fc=0, bc=255, k=8):
# P(fc) = k/16, P(bc) = (16-k)/16
if k == 0: return np.zeros(size) + bc
idx = np.random.random(size) < k/16
img = np.where(idx, fc, bc)
return img
def make_grid(size, fc=0, bc=255, k=8):
img = np.zeros(size) + bc
for i in range(k):
r, c = pts[i]
img[r::4, c::4] = fc
return img
def grid(img):
assert img.ndim == 2
patterns = [make_grid([4, 4], **kw) for kw in settings]
clrs = np.linspace(0, 255, len(settings)).astype(int)
delims = (clrs[1:] + clrs[:-1]) // 2
delims = np.asarray([0, *delims, 256])
idcs = [np.where((img >= st) & (img < ed)) for st, ed in zip(delims[:-1], delims[1:])]
img = img.copy()
for idx, pt in zip(idcs, patterns):
idxm4 = (idx[0] % 4, idx[1] % 4)
img[idx] = pt[idxm4]
return img
def grid_bts(img):
img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_GRAYSCALE)
img = grid(img).astype(np.uint8)
img = bytes(cv2.imencode('.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])[1])
return img
def noise(img):
assert img.ndim == 2
clrs = np.linspace(0, 255, len(settings)).astype(int)
delims = (clrs[1:] + clrs[:-1]) // 2
delims = np.asarray([0, *delims, 256])
idcs = [np.where((img >= st) & (img < ed)) for st, ed in zip(delims[:-1], delims[1:])]
img = img.copy()
for idx, kw in zip(idcs, settings):
img[idx] = make_noise(len(idx[0]), **kw)
return img
def noise_bts(img):
img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_GRAYSCALE)
img = noise(img).astype(np.uint8)
img = bytes(cv2.imencode('.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])[1])
return img
def main():
fname = sys.argv[1]
img = open(fname, 'rb').read()
img = grid_bts(img)
with open(fname, 'wb') as f:
f.write(img)
if __name__ == '__main__': main()
\ No newline at end of file
import subprocess as subp
import tempfile
import uuid
import os
from os import path
import sys
from .util import *
def pngquant(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
def main():
fname = sys.argv[1]
img = open(fname, 'rb').read()
img = pngquant(img)
with open(fname, 'wb') as f:
f.write(img)
if __name__ == '__main__': main()
\ No newline at end of file
import sys
import cv2
import numpy as np
def trunc_bts(img, l=4):
img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_GRAYSCALE)
img = trunc(img, l).astype(np.uint8)
img = bytes(cv2.imencode('.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])[1])
return img
def trunc(img, l=4):
assert img.ndim == 2
colors = np.linspace(0, 255, l).astype(int)
img_3d = np.expand_dims(img, 2)
dist = np.abs(img_3d - colors)
idx = np.argmin(dist, axis=2)
img = colors[idx]
return img
def main():
fname = sys.argv[1]
img = open(fname, 'rb').read()
img = trunc_bts(img)
with open(fname, 'wb') as f:
f.write(img)
if __name__ == '__main__': main()
\ No newline at end of file
import subprocess as subp
import tempfile
import uuid
import os
from os import path
def conv2png(img):
if img[:4] == b'\x89PNG':
return img
fname = path.join(
tempfile.gettempdir(),
uuid.uuid4().hex + '.png'
)
with open(fname, 'wb') as f:
f.write(img)
subp.Popen(
['convert', fname + '[0]', fname],
shell=True,
stdout=subp.PIPE,
stderr=subp.PIPE,
).communicate()
with open(fname, 'rb') as f:
img = f.read()
os.unlink(fname)
return img
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册