[英]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.