0

So basically, I'm screenshotting my screen and converting the format into an RGB format. After that i have 2 for-loops to go through every pixel and draw the correct color into the pixel. My programm is working, but is VERY slow... Is there a way to make it go faster?

Here is the code:

from PIL import ImageGrab
from graphics import *


win = GraphWin('screenshot',1000,1000)

def draw():
    for y in range(1000):
        for x in range(1000):
            r, g, b = rgb_img.getpixel((x,y))   
            head = Circle(Point(x,y),1)
            head.setFill(color_rgb(r,g,b))
            head.setWidth(0)
            head.draw(win)


while True:
    img = ImageGrab.grab()
    rgb_img = img.convert('RGB')
    draw()

1 Answers1

0

You could try multi-threading to make it faster

from PIL import ImageGrab
from graphics import *
import numpy as np
from threading import Thread

win = GraphWin('screenshot',1000,1000)

def draw(pixel_ranges):
    for y in pixel_ranges:
        for x in pixel_ranges:
            r, g, b = rgb_img.getpixel((x,y))   
            head = Circle(Point(x,y),1)
            head.setFill(color_rgb(r,g,b))
            head.setWidth(0)
            head.draw(win)

num_threads = 10
image_size = 1000

pixel_splits = np.split(np.arange(1000),num_threads)

n_threads = []
img = ImageGrab.grab()
rgb_img = img.convert('RGB')

for t in range(num_threads):
    thread = Thread(target = draw, args = (pixel_splits[t],))
    thread.start()
    n_threads.append(thread)

for t in n_threads:
    t.join()

Basically what i am doing here is i am creating a list of pixels from 0-1000 using np.arange() and splitting that list into 10 equal parts, we then create 10 threads that are responsible for populating the pixels in their range, so thread 0 gets pixels 0-100, thread 1 gets pixels 100-200 and so on, this should speed up your performance significantly

EDIT: The larger the number of threads the faster your code will be, but beware: If You have 4 CPU sockets, each CPU can have, up to, 12 cores and each core can have two threads. Your max thread count is, 4 CPU x 12 cores x 2 threads per core, so 12 x 4 x 2 is 96. Therefore the max thread count is 96 and max core count is 48, exceeding this or getting close to this thread count could fry your machine,

Imtinan Azhar
  • 1,725
  • 10
  • 26
  • Hmm, I see what you are doing, but the code is not quit compiling when i run it.I am getting a TypeError: draw() takes 1 positional argument but 100 were given – Elie Jamous Oct 21 '18 at 15:02
  • oh do this, (pixel_splits[t] , ) , more information on it here: https://stackoverflow.com/questions/3221655/python-threading-string-arguments, i will update the code to reflect this change – Imtinan Azhar Oct 22 '18 at 07:22