0

I'm writing a simple script for Dithering in python 3.4 using pygame and numpy. I already did it in processing without problems but I'm getting bad results with python.

This is my script in Python and this are the results I'm getting

from pygame import display, surfarray, image
import pygame
from pygame.locals import Color
import numpy as np

factor = 3

pygame.init()
imagen = image.load("download.jpg") #Pygame Surface
imagen_pix = surfarray.array3d(imagen)
width, height = imagen.get_width(),imagen.get_height()
screen = display.set_mode((width*2,height))

for y in range(height-1):
    for x in range(width-1):
        oldR, oldG, oldB = imagen_pix[x][y]

        newR = round((factor-1)*oldR/255.0)*(255.0/(factor-1))
        newG = round((factor-1)*oldG/255.0)*(255.0/(factor-1))
        newB = round((factor-1)*oldB/255.0)*(255.0/(factor-1))

        imagen_pix[x][y] = (newR, newG, newB)

        errR = oldR-newR
        errG = oldG-newG
        errB = oldB-newB

        r, g, b = imagen_pix[x+1][y]
        r += errR*7.0/16.0
        g += errG*7.0/16.0
        b += errB*7.0/16.0
        imagen_pix[x][y] = (r, g, b)

        r, g, b = imagen_pix[x-1][y+1]
        r += errR * 3.0 / 16.0
        g += errG * 3.0 / 16.0
        b += errB * 3.0 / 16.0
        imagen_pix[x][y] = (r, g, b)

        r, g, b = imagen_pix[x][y+1]
        r += errR * 5.0 / 16.0
        g += errG * 5.0 / 16.0
        b += errB * 5.0 / 16.0
        imagen_pix[x][y] = (r, g, b)

        r, g, b = imagen_pix[x + 1][y+1]
        r += errR * 1.0 / 16.0
        g += errG * 1.0 / 16.0
        b += errB * 1.0 / 16.0
        imagen_pix[x][y] = (r, g, b)

imagenNueva = surfarray.make_surface(imagen_pix)

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.blit(imagen, (0, 0))
    screen.blit(imagenNueva, (width, 0))
    display.update()
pygame.quit()

This is the result in Python

This is the result in Processing

Whats the problem with my python script?

  • Since `x` stays in `range(width-1)`, the line with `imagen_pix[x-1][y+1]` seems to cause a negative index. Should that be `x+1` perhaps? Also, you're reading from various locations, but always writing to `imagen_pix[x][y]`. Is that your intention? At a first glance that seems that only the final assignment to `imagen_pix[x][y]` would be used this way. – brm Jan 20 '18 at 19:23
  • `imagen_pix[x-1][y+1]` is part of the algorith for Dithering. I changed to `range(1,width-1)` and `range(1,height-1)` to avoid the negative index but no luck. And yes, my intention is to read and update 5 times `imagen_pix` in each iteration. – Misael Alarcon Jan 23 '18 at 20:30

0 Answers0