【问题标题】:How to load your own labels for the classifier如何为分类器加载自己的标签
【发布时间】:2021-10-18 16:11:59
【问题描述】:

我是这里的新手。我有一个列出所有图像的文件路径,但我坚持将标签连接到图像。我有一个包含图像编号和标签的 CSV 文件。解决这个问题的最佳方法是什么?仅供参考,我使用的是预训练模型 (Python)。

谢谢!

【问题讨论】:

  • 欢迎来到 Stack Overflow @7006。我怀疑您需要提供更多详细信息,例如代码的 sn-ps、您尝试过的内容、具体的错误消息等,以便在此处获得有用的反馈。

标签: python label image-classification


【解决方案1】:

我想你想创建一个带有标签作为维度的 numpy 图像数组?您可以使用以下代码:

def class_segmentation(dir_path,df):
    
    """ takes a given folder and splits it into respective classes based on the csv file labels
    mapped to the names of the files
    dir_path = path of the directory which needs to be segmented
    classes = list of classes present in the dataset, as string
    
    """
    image_list = os.listdir(dir_path)
    classes = get_classes(df)
    
    for clas in classes:
        os.makedirs(os.path.join(dir_path,clas))
    
    for image in image_list:
        if(image in df['image_extensions'].tolist()):
            label = (df[df['image_extensions']==image]['label']).tolist()[0]
            image_path_src = os.path.join(dir_path, image)
            dest = os.path.join(dir_path, str(label))
            image_path_dest = os.path.join(dest,image)
            shutil.move(image_path_src, image_path_dest)

接下来需要将这些图片转换为numpy数组,并加载对应的标签。

def img_to_array_data(dir_path, classes):
    data_array = []
    for clas in classes:
        classpath = os.path.join(dir_path,str(clas))
        for img in os.listdir(classpath):
            img_array = cv2.imread(os.path.join(classpath,img))
            data_array.append([img_array,clas])
            
    random.shuffle(data_array)    
    
    X =[]
    y =[]

    for features, label in data_array:
        X.append(features)
        y.append(label)
        
    X = np.array(X).reshape(-1, dim[0], dim[0], 3)
    X = X.astype('float32')
    X /= 255
    
    Y = np_utils.to_categorical(y, 5)
    
    return X,Y

当然,不要忘记导入所有必要的库:osnp_utils 等。

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    相关资源
    最近更新 更多