0

So I have a pixel array from an image using PIL. I take the pixel array and randomize the order of the array. Then I use a quicksort on the array and I would like to know how to visualize the sorting of the pixels. I was thinking I could do this using Matplotlib, however, I'm just unsure of how to do this. Here's the code I use to grab the image data and sort it. I can get it to sort the image and output, however, I would like to see the sorting in real-time.

import random
from PIL import Image
import numpy as np
import scipy.misc as smp
import matplotlib.pyplot as plt

def quickSort(alist):
       quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):
   if first<last:

       splitpoint = partition(alist,first,last)

       quickSortHelper(alist,first,splitpoint-1)
       quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
   pivotvalue = alist[first]

   leftmark = first+1
   rightmark = last

   done = False
   while not done:

       while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
           leftmark = leftmark + 1

       while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
           rightmark = rightmark -1

       if rightmark < leftmark:
           done = True
       else:
           temp = alist[leftmark]
           alist[leftmark] = alist[rightmark]
           alist[rightmark] = temp

   temp = alist[first]
   alist[first] = alist[rightmark]
   alist[rightmark] = temp

   return rightmark

img = Image.open('image2.png')

pixelValues = list(img.getdata())
data = np.zeros((1024, 1024, 3), dtype=np.uint8)

for i in  xrange(len(pixelValues)):
    pixelValues[i] = pixelValues[random.randint(0, 1048575)]
quickSort(pixelValues)
writtenImg = Image.new("RGB", (1024,1024), "white")

writtenImg.putdata(pixelValues)
DavidG
  • 24,279
  • 14
  • 89
  • 82
jacksons123
  • 171
  • 10
  • Sorry, I don't know matplotlib, so I can't answer your question. Do you want the image to show the movement of every single pixel as it's sorted? Or just the result of each recursive qsort call? – PM 2Ring Dec 12 '17 at 17:07
  • BTW, you _aren't_ randomising `pixelValues`. Your shuffling algorithm doesn't preserve its data: it repeats some pixels, which causes other pixels to get lost. See [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) for details. Both the standard random module and Numpy's random module provide a Fisher–Yates shuffle. Also, in Python you can swap stuff without a `temp` variable, eg `a, b = b, a`. – PM 2Ring Dec 12 '17 at 17:13
  • See here https://stackoverflow.com/questions/12570859/how-to-show-pil-images-on-the-screen – Omni Dec 12 '17 at 21:36

0 Answers0