I'm a hobby programer and I had an idea for pixelating images and I wrote it. I was wondering how would a better programer write the same function.
I want to learn and I think that this would help me a lot to see how code is supposedto be written, also my code is quite slow and i would like to make it swifter.
I use PIL for image manipulation, pygame for window and numpy for math. after this code i return img that is in PIL format and pass it to pygame with fromstring.
This code divides the image into blocks defined by pixSize and then thakes RGB value from all the pixels in that block and finds median value with witch then that block is colored and then it moves on to next block and and does the same.
Here is my code
def pixelateImage(self, img, pixSize):
print(img.size[1])
n = 0
ny = 0
blockInfo = []
for i in range(int(img.size[0]/pixSize)*int(img.size[1]/pixSize)):
colVal = (randrange(0,256), randrange(0,256), randrange(0,256))
if n+1 > int(img.size[0]/pixSize):
n = 0
ny += 1
xs = range(pixSize*n, pixSize*(n+1))
ys = range(pixSize*ny, pixSize*(ny+1))
RGB = []
for x in xs:
for y in ys:
cModeRGB = []
rgb = img.getpixel((x,y))
for i in rgb:
if i == 0:
cModeRGB.append(0)
continue
cMode = i / 255
cModeRGB.append(cMode)
RGB.append(cModeRGB)
RGBc = np.array(RGB)
RGB = []
for i in np.median(RGBc, axis=0):
RGB.append(int(i * 255))
rgbMid = (RGB[0], RGB[1], RGB[2])
for x in xs:
for y in ys:
img.putpixel((x,y), rgbMid)
n += 1
return img