如何在数组类型中初始化变量,如何为其赋值?

时间:2016-02-10 10:10:24

标签: python image-processing

我有一个图像,我想找到块中的中位数,然后显示它。这是我的代码:

img = cv2.imread('pic.png', 0)

win = 5   
height, width = img.shape    

MedianOfBlock = {}  

for i in range(0, (height-2*win)):
  for j in range(0, (width- 2*win)):
     block = np.array(img[i:i+win, j:j+win])

     # Compute the median in each window
     MedianOfBlock[i,j] = np.median(block)

但是为了进一步处理,MedianOfBlock应该是数组类型。不是字典类型。我该怎么做?或者有没有办法以数组形式进行上述处理而不是字典类型?即如何将MedianOfBlock初始化为数组赋值? 感谢。

2 个答案:

答案 0 :(得分:0)

如您所知,维度可以:

height_max = height - 2 * win
width_max = width - 2 * win
array_form = [
  [ MedianOfBlock[i,j] for j in range(width_max) ] for i in range(height_max)
]

但我建议您从一开始就使用矩阵数据结构:

img = cv2.imread('pic.png', 0)

win = 5   
height, width = img.shape

MedianOfBlock = []

for i in range(height-2*win):
  MedianOfBlock.append([])
  for j in range(width-2*win):
     block = np.array(img[i:i+win, j:j+win])

     # Compute the median in each window
     MedianOfBlock[i].append(np.median(block))

答案 1 :(得分:0)

以下是否适合您?它应该形成一个列表列表

mg = cv2.imread('pic.png', 0)

win = 5   
height, width = img.shape    

MedianOfBlock = []

for i in range(0, (height-2*win)):
  row = []
  for j in range(0, (width- 2*win)):
     block = np.array(img[i:i+win, j:j+win])

     # Compute the median in each window
     row.append(np.median(block))

  MedianOfBlock.append(row)

访问它的方式与代码中的方式相同

MedianOfBlock[i][j]