0

我正在使用Python和Numpy来获取同一像素尺寸的多个图像并创建一个二维数组,因此数组的每一行代表一个图像,每一列代表像素某个位置。连接numpy数组中的图像

为了实现这一点,我已经阅读了图像文件并尝试使用numpy.concatenate。该代码是

#url of picture data 
X_p = data.link 
#list for storing the picture data 
X= [] 

#read in the image from the url, and skip poster with 404 error 
for url in X_p: 
    try: 
     loadimg = urllib.request.urlopen(url) 
     image_file = io.BytesIO(loadimg.read()) 
     img = Image.open(image_file) 

     #Concatenate to linearize 
     X.append(np.concatenate(np.array(img))) 

    #404 error 
    except urllib.error.HTTPError as err: 
     if err.code == 404: 
      continue 
     else: 
      raise 

#cast the list into numpy array  
X = np.array(X) 
#test to see if X is in correct dimension 
print(X.shape) 

我跑这个代码和X的形状出来,在这种格式每一次

(图像的数量,高度X宽度,3)

,例如,如果我加载的200x200像素12页图像的URL,结果是

(12,40000,3)

我需要的是在最后摆脱3的,这是很难的时候,不甚至了解3从哪里来。

我假设我遇到的问题是在错误的地方追加或连接。当我删除np.concatenate时,它只是显示(12,200,200,3)。

我在网上搜索numpy图像处理和连接,但我没有跑过任何可以解释和解决发生的事情。

任何和所有的帮助表示赞赏。预先感谢您花时间阅读这篇文章并回答..

回答

0

我想通了这个问题。我对数组的维度很好奇,所以我搜索了一些问题,要求增加或减少1维。我跑过一个解释3代表什么的帖子。

How can I save 3D array results to a 4D array in Python/numpy?

Image.open().convert("L") 

并没有为我工作,所以我只好用一招

with Image.open().convert("L") as img 

我加了这一行后的for循环,尺寸问题得到了解决。