1

I'm trying to create an ASCII photo generator in python by following a guide online, so what I did was I converted the image date to RGB tuples and put them in a 2d array. I converted this 2d array to a brightness array by taking the average of all RGB values. But this brightness array shows different output when I print it again compared to printing it while assigning the values.

Initially it shows the correct output, but when I print it again it shows the same values in all the rows of the matrix.

from PIL import Image
import math

im = Image.open("smallimage.jpg")
print(im.size)

rows,cols = (im.size[0],im.size[1])
print(rows,cols)
arr = [[0]*cols]*rows

arr = list(im.getdata())
arr = [arr[i*cols: (i+1)*cols] for i in range(rows)]

brightness_matrix = [[0]*cols]*rows

for row in range(rows):
    for col in range(cols):
        brightness_matrix[row][col] = math.floor((arr[row][col][0] + arr[row][col][1] + arr[row][col][2])/3)
        print(brightness_matrix[row][col],end = " ")
    print()

for row in range(rows):
    for col in range(cols):
        print(brightness_matrix[row][col],end=" ")
    print()

It's the last row of the original output that keeps repeating in the new output.

The output when I run this program

Monolith
  • 1,067
  • 1
  • 13
  • 29
jil25
  • 13
  • 3
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – jasonharper Aug 02 '20 at 22:13

1 Answers1

1

The error is during the initialization of your 2D list - arr = [[0]*cols]*rows . This will cause the inner list of [0,0,...] to be repeated rows number of times since it is just copying the address of the inner list. See the example below. Everytime you modify any element in a row all the elements in every row is updated.

>>> arr = [[0]*2]*3
>>> arr[0][0] = 1
>>> arr
[[1, 0], [1, 0], [1, 0]]

Suggested code : arr = [ [0]*cols for i in range(rows)]

In your print statements, the first print of array is being done after every modification so it is printing the correct latest values but also updating earlier assigned values. This is the reason of the second print to show repeated values.