[英]Flattening 2D array 1D Sum
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], ..]我有一个二维数组,它的元素是一个 RGB 数组,例如:[ [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, ..]我试图将每个数组展平为 RGB 的平均值,因此对于上面的 2D 数组,它将是:[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
.所以对于我的 for 循环,它告诉我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.这对我来说很奇怪,因为打印语句显示了数组的所有索引,以及将 go 放入该索引的元素。
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 = []
.您有一个空list
brightness_array = []
。 There's nothing in there.里面什么都没有。 You can't index an empty list
.您不能索引空list
。 Perhaps you wanted brightness_array.append(sum(x))
.也许您想要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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.