繁体   English   中英

使用 python 手动混合图像的像素

[英]mixing pixels of an image manually using python

我正在尝试创建一种混合图像像素的算法,并且可以像以前一样使用图像,但我不知道这样做。

我正在使用 python 和 pil,但我可以使用其他库。

例子:在此处输入图片说明 在此处输入图片说明然后回到在此处输入图片说明

谢谢你。

这应该这样做。 没有错误处理,它不遵循 pep8 标准,它使用慢 PIL 操作并且它不使用参数解析库。 我敢肯定它还有其他不好的地方。

它的工作原理是在 python 的随机数生成器中使用加扰图像的不变量。 使用大小的散列。 由于大小不会改变,因此构建在其上的随机序列对于共享相同大小的所有图像将是相同的。 该序列用作一对一映射,因此它是可逆的。

该脚本可以从 shell 调用两次以创建两个图像,“scrambled.png”和“unscrambled.png”。 “Qfhe3.png”是源图像。

python scramble.py scramble "./Qfhe3.png"
python scramble.py unscramble "./scrambled.png"
#scramble.py
from PIL import Image
import sys
import os
import random

def openImage():
    return Image.open(sys.argv[2])

def operation():
    return sys.argv[1]

def seed(img):
    random.seed(hash(img.size))

def getPixels(img):
    w, h = img.size
    pxs = []
    for x in range(w):
        for y in range(h):
            pxs.append(img.getpixel((x, y)))
    return pxs

def scrambledIndex(pxs):
    idx = list(range(len(pxs)))
    random.shuffle(idx)
    return idx

def scramblePixels(img):
    seed(img)
    pxs = getPixels(img)
    idx = scrambledIndex(pxs)
    out = []
    for i in idx:
        out.append(pxs[i])
    return out

def unScramblePixels(img):
    seed(img)
    pxs = getPixels(img)
    idx = scrambledIndex(pxs)
    out = list(range(len(pxs)))
    cur = 0
    for i in idx:
        out[i] = pxs[cur]
        cur += 1
    return out

def storePixels(name, size, pxs):
    outImg = Image.new("RGB", size)
    w, h = size
    pxIter = iter(pxs)
    for x in range(w):
        for y in range(h):
            outImg.putpixel((x, y), next(pxIter))
    outImg.save(name)

def main():
    img = openImage()
    if operation() == "scramble":
        pxs = scramblePixels(img)
        storePixels("scrambled.png", img.size, pxs)
    elif operation() == "unscramble":
        pxs = unScramblePixels(img)
        storePixels("unscrambled.png", img.size, pxs)
    else:
        sys.exit("Unsupported operation: " + operation())

if __name__ == "__main__":
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM