Home > database >  how to read csv file and pass its values to a function parameters
how to read csv file and pass its values to a function parameters

Time:01-23

I have a csv file having one column and the values it contains like this: here

and this function

def yolo_to_coco(x_center, y_center, w, h,  image_w, image_h):
  w = w * image_w
  h = h * image_h
  x1 = ((2 * x_center * image_w) - w)/2
  y1 = ((2 * y_center * image_h) - h)/2
  return [x1, y1, w, h]``

when I pass value to this function image_w and image_h I am passing from my own it is not in the csv

test = yolo_to_coco(53.854, 2912.798, 398.71, 57.202,1024,1024) 

the get the required result

[-148993.02399999998, 2953417.7279999997, 408279.04, 58574.848]

I want to get each value from this file and pass to this function and the store in another csv file.

CodePudding user response:

You can use dataframe.apply(function) method. With this method you can apply this function to every row. Let's create a dummy df.

import pandas as pd
d = {'bbox': [[53.854, 2912.798, 398.71, 57.202],[31, 12,120, 20],[17, 72,170, 720]]}
df = pd.DataFrame(data=d)

But you don't need to create dummy df. You will read as

df = pd.read_csv ('/content/drive/MyDrive/bbox_file.csv')

let's create function. First argument will be row value. We will specify extra 2 arguments (image_w, image_h)

def yolo_to_coco(bbox,  image_w, image_h):
    row_list = list(bbox[1:-1].split(","))
    row_list = [float(i) for i in row_list]
    x_center, y_center, w, h = row_list
    w = w * image_w
    h = h * image_h
    x1 = ((2 * x_center * image_w) - w)/2
    y1 = ((2 * y_center * image_h) - h)/2
    return [x1, y1, w, h]

Now, We can apply this function to bbox column.You can pass any image_w,image_h values. It will create a pandas.series

df_coco_series = df["bbox"].apply(yolo_to_coco,image_w = 1024,image_h = 1024)

Finally converting to pandas.dataframe

df_coco = df_coco_series.to_frame()
print(df_coco)
  • Related