I am trying to understand why my solution to the problem is not working.
I have a 2D array, its elements are an array of RGB, for example: [ [30, 60, 90], [30, 51, 255], ..]
What I am trying to flatten every array into the average of the RGB, so for the 2D array above it would be: [60, 366, ..]
Here is my attempt:
# import image processing libraries
from __future__ import print_function
import sys
from PIL import Image
import numpy as np
# open a specific image from file and save it as an image object to print its info
im = Image.open("ascii-pineapple.jpg", 'r')
print(im.format, im.size, im.mode)
# save image pixels as a list of tuples in the form of RGB
pix_val = list(im.getdata())
pix_array = [list(item) for item in pix_val] #turn tuples into arrays
brightness_array = []
for i, x in enumerate(pix_array):
brightness_array[i] = sum(x)
print(str(i) + " " + str(sum(x)))
so for my for loop, it tells me IndexError: list assignment index out of range
. Which is quite odd for me, because the print statement shows all the indices of the array, and the element that would go into that index.
I am new to this, so any help pointing out what I am doing wrong would be appreciated. Thanks!
You have an empty list
brightness_array = []
. There's nothing in there. You can't index an empty list
. Perhaps you wanted brightness_array.append(sum(x))
.
Change the code to:
brightness_array = []
for i, x in enumerate(pix_array):
brightness_array.append(sum(x)) # will append the `sum` to the `brightness_array`
print("{} {}".format(i, sum(x)))
Here's a way:
pix_array = [list(item) for item in pix_val]
brightness_array = [sum(map(lambda x:x/3,sublst)) for sublst in pix_array]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.