user2023413
user2023413

Reputation:

How to reorder pixels

I have searched on Google but I couldn't find anything.

I want to create a Python script that can import an image, change the order of pixels, and save an output image.

I have worked with Python a lot, but only with the built-in libraries. So if I have to use new commands, please describe it as much as you can.

Upvotes: 6

Views: 3694

Answers (2)

mmgp
mmgp

Reputation: 19241

import sys
import random
from PIL import Image

BLOCKLEN = 64 # Adjust and be careful here.

img = Image.open(sys.argv[1])
width, height = img.size

xblock = width / BLOCKLEN
yblock = height / BLOCKLEN
blockmap = [(xb*BLOCKLEN, yb*BLOCKLEN, (xb+1)*BLOCKLEN, (yb+1)*BLOCKLEN)
        for xb in xrange(xblock) for yb in xrange(yblock)]

shuffle = list(blockmap)
random.shuffle(shuffle)

result = Image.new(img.mode, (width, height))
for box, sbox in zip(blockmap, shuffle):
    c = img.crop(sbox)
    result.paste(c, box)
result.save(sys.argv[2])

Example input, BLOCKLEN = 1, BLOCKLEN = 64, BLOCKLEN = 128:

enter image description here enter image description here enter image description here enter image description here

Upvotes: 14

Emanuele Paolini
Emanuele Paolini

Reputation: 10172

You should look for the PIL library link

Upvotes: -1

Related Questions