Numpy:使用序列设置数组元素

时间:2016-05-17 23:47:52

标签: python arrays numpy

我不确定这段代码我做错了什么:

import cv2
from matplotlib import image as img
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import axis

img = cv2.imread('popi.png', 0)
cv2.imshow('lel', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
a = np.shape(img)
iloscpixeli = a[0] * a[1]
print(iloscpixeli)
b = np.zeros((256, 1))
H = np.zeros((a[0], a[1]))
# czest = np.zeros((256, 1))
# probf = np.zeros((256, 1))
# probc = np.zeros((256, 1))
# cum = np.zeros((256, 1))
dim = np.shape(img)
wyjscie = np.zeros(dim)
H = np.zeros(dim)
print("dim", dim)
czest = np.zeros(dim)
probc = np.zeros(dim)
# print("r",czest)
probf = np.zeros(dim)
cum = np.zeros(dim)
for i in range(1, a[0]):
    for j in range(1, a[1]):
        wartosc = img[i, j]
        czest[wartosc + 1] = (czest[wartosc + 1] + 1)
        probf[wartosc + 1] = czest[wartosc + 1] / iloscpixeli

suma = 0
nobins = 255
d = np.zeros((256, 1))
d1 = np.shape(d)
d11 = d1[0]

for i in range(1, d11):
    suma = suma + czest[i]
    cum[i] = suma
    probc[i] = cum[i] / iloscpixeli
    wyjscie[i] = np.around(probc[i] * nobins)
wyjscie=wyjscie.tolist()
for i in range(1, a[0]):
    for j in range(1, a[1]):
        H[i, j] = wyjscie[img[i,j] + 1]

cv2.imshow('wyrownany', H)

这一行(是的,最后:C):

H[i, j] = wyjscie[img[i,j] + 1] 

给我错误ValueError:使用序列设置数组元素。尝试修复已检查有关将'wyjscie'从数组更改为列表..但不能正常工作。 我寻求任何帮助。当你寻找代码时,它很棒,可能我做了一些愚蠢的事情......但是有一行czest[wartosc + 1] = (czest[wartosc + 1] + 1)并且效果很好......

1 个答案:

答案 0 :(得分:1)

  • H是一个numpy数组,dtype = float,因为它是默认值。它的形状是2d
  • 您想要插入wyjscie[img[i,j] + 1]
  • wyjscie本身是一个形状为2d
  • 的numpy数组
  • 您将wyjscie转换为列表,但此列表将是嵌套列表,因为原始dim为2d
  • 您在嵌套列表中进行索引,因此获取一个列表并将此列表放入一个包含float的单元格=将序列/列表放入数组元素 ERROR
  • (你很光彩:-D)