we multi-threading bois

This commit is contained in:
iou1name 2017-12-10 16:52:14 -05:00
parent 0759ec4199
commit cc9fedcb83

View File

@ -7,6 +7,7 @@ import os
import time import time
import random import random
import colorsys import colorsys
import threading
import numpy as np import numpy as np
from PIL import Image from PIL import Image
@ -14,7 +15,8 @@ from PIL import Image
class Mosiac(): class Mosiac():
def __init__(self): def __init__(self):
self.numClusters = 8 self.numClusters = 8
self.tolerance = 0.5 self.tolerance = 0.1
self.numThreads = 4
self.imageBank = {} self.imageBank = {}
self.clusters = [] self.clusters = []
@ -28,7 +30,7 @@ class Mosiac():
self.matrixSize = None self.matrixSize = None
def openBigImage(self, imagePath, mat=(40,20)): def openBigImage(self, imagePath, mat=(20,40)):
""" """
Opens and initializes the big image. Opens and initializes the big image.
""" """
@ -40,12 +42,37 @@ class Mosiac():
self.bigImageSize = (self.tileSize[0]*mat[0], self.tileSize[1]*mat[1]) self.bigImageSize = (self.tileSize[0]*mat[0], self.tileSize[1]*mat[1])
def initImageBank(self, root, size=(200,200)): def initImageBank(self, root):
""" """
Calculates the average pixel value of all the images in the directory. Calculates the average pixel value of all the images in the directory.
This is the thread controller.
""" """
then = time.time() then = time.time()
for file in os.listdir(os.path.join(root, "images")): files = os.listdir(os.path.join(root, "images"))
thread_files = []
num = len(files) // self.numThreads
for n in range(self.numThreads):
t_files = [file for file in files[n*num:n*num+num]]
thread_files.append(t_files)
thread_files[-1] += [file for file in files[-(len(files) % num):]]
threads = []
for t_files in thread_files:
t = threading.Thread(target=self.initImageBankWorker,
args=((root, t_files)))
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"initImageBank took: {time.time()-then} seconds.")
def initImageBankWorker(self, root, files):
"""
Thread worker.
"""
for file in files:
image = Image.open(os.path.join(root, "images", file)) image = Image.open(os.path.join(root, "images", file))
if image.mode == "P": if image.mode == "P":
@ -63,7 +90,6 @@ class Mosiac():
# (255,255,255,255) else pixel, image.getdata()))) # (255,255,255,255) else pixel, image.getdata())))
self.imageBank[mean] = image self.imageBank[mean] = image
print(f"initImageBank took: {time.time()-then} seconds.")
def debugImageBank(self): def debugImageBank(self):
@ -223,7 +249,7 @@ if __name__ == "__main__":
mosiac = Mosiac() mosiac = Mosiac()
mosiac.openBigImage(os.path.join(args.root, "big.jpg")) mosiac.openBigImage(os.path.join(args.root, "big.jpg"))
mosiac.initImageBank(**vars(args)) mosiac.initImageBank(args.root)
# mosiac.debugImageBank() # mosiac.debugImageBank()
mosiac.initClusters() mosiac.initClusters()
mosiac.buildMatrix() mosiac.buildMatrix()