【问题标题】:np.reshape(): Converting an image into a feature array based on rgb intensitiesnp.reshape():将图像转换为基于 rgb 强度的特征数组
【发布时间】:2019-07-11 01:49:53
【问题描述】:

我正在尝试使用 sklearn 的 Mean-Shift 算法分割彩色图像。 我有以下代码:

import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from itertools import cycle
from PIL import Image

image = Image.open('sample_images/fruit_half.png')
image = np.array(image)

#need to convert image into feature array based on rgb intensities
flat_image = np.reshape(image, [-1,3])

我正在尝试将图像转换为基于 rgb 强度的特征数组,以便进行聚类。 但是,我收到以下错误:

ValueError: cannot reshape array of size 3979976 into shape (3)

我不确定为什么会收到此错误以及如何解决此问题。任何见解都值得赞赏。

【问题讨论】:

    标签: python numpy scikit-learn computer-vision mean-shift


    【解决方案1】:

    这是因为你正在加载的图像没有RGB值(如果你看尺寸,最后一个是4。

    您需要先将其转换为 RGB,如下所示:

    image = Image.open('sample_images/fruit_half.png').convert('RGB')
    image = np.array(image)
    
    # Now it works
    flat_image = np.reshape(image, [-1,3])
    

    【讨论】:

    • 您是如何判断图像没有 RGB 值的?我不明白你说的最后一个维度是 4 是什么意思。
    • 因此,当您加载数据并将其转换为 numpy 时,您可以使用 image.shape 检查其维度。它将显示(#rows、#columns、#features)。在你的情况下,特征的数量是 4,所以它不能是 RGB 值(因为 RGB 是 3)
    • 什么样的图片会有4个特征?
    • 我不完全确定,但可能是 3 个 RGB 通道 + 1 个透明度通道。
    • @ceno980 PNG 支持 A (alpha) 通道表示透明度的 RGBA 图像。
    猜你喜欢
    • 2021-04-02
    • 2010-10-15
    • 2014-02-26
    • 2014-12-22
    • 2018-08-22
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多