Python 实作 Ordered algorithm

Ordered dithering是 Dithering algorithm 中的一个常见的算法

threshold map公式

根据维基百科中所述的公式可以先写一个产生 threshold map的方法:

产生矩阵

import numpy as np
import sys

def getMatrix(exp):
    if exp == 0: return None
    if exp == 1: return np.array([[0,2],[3,1]])
    Mb = np.array([[0,2],[3,1]])
    for i in range(1,exp):
        Mn = np.vstack([np.hstack([4*Mb, 4*Mb+2]),np.hstack([4*Mb+3, 4*Mb+1])])
        Mb = Mn;
    return Mn

exp = int(sys.argv[1]) #从输入中获得指数
if exp==0:print('指数必须大于等于1')
n = 2**exp          #二值图的大小参数
M = getMatrix(exp) #得到原始矩阵
colorSpace = int(256/((2**exp)**2)) 

print("二值图("+str(n)+"x"+str(n)+")")
print('colorspace:'+str(colorSpace))
print('原始矩阵:')
print(M)
print('颜色矩阵:')
print(M*colorSpace)

然后就是图片的处理部分:

# -*- coding: utf-8 -*-
from skimage import io
import numpy as np

#exp = power of two 2^exp
def getMatrix(exp):
    if exp == 1:return np.array([[0,2],[3,1]])
    Mb = np.array([[0,2],[3,1]])
    for i in range(1,exp):
        Mn = np.vstack([np.hstack([4*Mb,4*Mb+2]),np.hstack([4*Mb+3,4*Mb+1])])
        Mb = Mn;
    return Mn

pow = 3  #修改pow产生不同大小的矩阵 
n = 2**pow
colorSpace = int(256/(n**2))
half = colorSpace*getMatrix(pow)
print(str(n)+'x'+str(n))
print(half)

def dither(pixels,i,j):
    x = i % n
    y = j % n
    value = half[x,y]
    return 255 if pixels>value else 0

img = io.imread('pic.jpg')
rows,cols,dims = img.shape
for i in range(0,rows):
    for j in range(0,cols):
        for k in range(0,3):
            img[i,j,k] = dither(img[i,j,k],i,j)
            
io.imshow(img)
io.imsave(str(n)+'x'+str(n)+'.jpg', img)
print('done')

首先看下原图效果(图片来自网上)

Python 实作 Ordered algorithm_第1张图片
原图

处理后的结果分别

Python 实作 Ordered algorithm_第2张图片
2x2 Dithering

Python 实作 Ordered algorithm_第3张图片
4x4 Dithering

Python 实作 Ordered algorithm_第4张图片
8x8 Dithering

Python 实作 Ordered algorithm_第5张图片
16x16 Dithering

如有疑问请留言欢迎交流

你可能感兴趣的:(Python 实作 Ordered algorithm)