无法使用'rfind'函数从文件路径中提取动物名称

时间:2015-04-22 06:49:23

标签: python string dictionary

无法使用rfind函数从文件路径中提取动物名称。

动物名称将用作词典index = {}

中的键

我的png文件路径是:c:\users\intel\desktop\folder\elephant.png

运行此代码后,

import ZernikeMoments
import numpy as np
import argparse
import cPickle
import glob
import cv2


ap = argparse.ArgumentParser()
ap.add_argument("-a", "--animals", required = True,
    help = "Path where the animals will be stored")
ap.add_argument("-i", "--index", required = True,
    help = "Path to where the index file will be sotred")
args = vars(ap.parse_args())


desc = ZernikeMoments(21)
index = {}

for animalPath in glob.glob(args["animals"] + "/*.png"):
    # parse out the name, load image and convert to grayscale
    animal = animalPath[animalPath.rfind("/") + 1: ].replace(".png", "")
    image = cv2.imread(animalPath, 0)

    image = cv2.copyMakeBorder(image, 15, 15, 15, 15,
        cv2.BORDER_CONSTANT, value = 255)
    thresh = cv2.bitwise_not(image)
    thresh[thresh > 0] = 255

    outline = np.zeros(image.shape, dtype = "uint8")
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, 
        cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
    cv2.drawContours(outline, [cnts], -1, 255, -1)

    moments = desc.describe(outline)
    index[animal] = moments

我得到c:\users\intel\desktop\folder\elephant作为字典键。 目的是将字典键设为elephant

1 个答案:

答案 0 :(得分:0)

您可以使用ntpath

执行此操作
import ntpath
a_path = "c:\users\intel\desktop\folder\elephant.png"
>>>ntpath.basename(a_path)
'elephant.png'
>>>ntpath.basename(a_path).split(".")[0]
'elephant'

或者只是使用ntpathos

>>>os.path.splitext(ntpath.basename(a_path))[0]
'elephant'