ValueError:无法将字符串转换为float:left_column_pixel

时间:2017-03-30 09:50:57

标签: python-3.x csv pandas opencv dataframe

l无法读取img() opencv中pandas的像素值,这里是我的代码和报告的错误

import cv2
import numpy as np
import csv
import os
import pandas as pd
path_csv='/home/'
npa=pd.read_csv(path_csv+"char.csv", usecols=[2,3,4,5], header=None)
nb_charac=npa.shape[0]-1

#stock the actual letters of your csv in an array
characs=[]
cpt=0
#take characters
f = open(path_csv+"char.csv", 'rt')
reader = csv.reader(f)
for row in reader:
    if cpt>=1: #skip header
        characs.append(str(row[1]))
    cpt+=1

#open your image
path_image= '/home/'
img=cv2.imread(os.path.join(path_image,'image1.png'))

path_save= '/home/2/'
i=0
#for every line on your csv,
for i in range(nb_charac):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i]

    #actual cropping of the image (easy with numpy)
    img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    i+=1



    #charac=charac.strip('"\'')
    #x=switch(charac)
    #saving the image
    cv2.imwrite(path_save+str(charac)+"_"+str(i)+"_"+str(img_charac.shape)+".png",img_charac)
    img_charac2 = 255 - img_charac
    cv2.imwrite(path_save +str(charac)+ "_switched" + str(i) + "_" + str(img_charac2.shape) + ".png", img_charac2)
    print(i)

我收到了以下错误

  img_charac=img[int(coords[2]):int(coords[3]),int(coords[0]):int(coords[1])]
  File "/usr/lib/python2.7/dist-packages/pandas/core/series.py", line 79, in wrapper
    return converter(self.iloc[0])
ValueError: invalid literal for int() with base 10: 'left_column_pixel'

错误与这行代码有关:

img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]

这样我的变量坐标如下:

>>> coords=npa.iloc[[1]]
>>> coords
    2    3     4     5
1  38  104  2456  2492

并且image_char中所需的列2,3,4,5的不同值为:

>>> coords[2]
1    38
Name: 2, dtype: object
>>> coords[3]
1    104
Name: 3, dtype: object
>>> coords[4]
1    2456
Name: 4, dtype: object
>>> coords[5]
1    2492
Name: 5, dtype: object

我更新了img_charac的行,如下所示

 img_charac = img[int(float(coords[2].values[0])):int(float(coords[4].values[0])), int(float(coords[3].values[0])):int(float(coords[5].values[0]))]

我已经没有了

ValueError: invalid literal for int() with base 10: 'left_column_pixel'

但是我收到了以下错误:

ValueError: could not convert string to float: left_column_pixel

我注意到在循环img_charac之外工作

1 个答案:

答案 0 :(得分:1)

我认为发生ValueError是因为您在for循环的第一次迭代中正在读取csv文件的标题行。标头包含无法转换为整数的字符串标签:

  • for i in range(nb_charac)将以i作为第一个值0开头。
  • 然后,coords=npa.iloc[[i]]将返回csv文件的第一行(第0行)。
  • 由于您已在header=None中设置了npa=pd.read_csv(path_csv+"char.csv", usecols=[2,3,4,5], header=None),因此您会对标题行中的字符串进行迭代。

因此,请设置header=0for i in range(1, nb_charac)