Question: Create a python script to convert an object detection annotations csv file into a json file in the format of a dictionary with keys images
Create a python script to convert an object detection annotations csv file into a json file in the format of a dictionary with keys "images" and "annotations". Value for the "images" key should be a list of entries, one for each image of the form filename": imagename, "height" : height, "width" : width, id : imageid Value of the "annotations" key should be a list of entries, one for each bounding box of the form imageid : imageid "bbox" : xmin ymin, xmax, ymax "categoryid : bboxlabel Our current csv file has the first column of data for the filename, the second column has the bounding box or "bbox" for X the third column has the bounding box or "bbox" for Y the fourth column has the image width, the fifth column has the image height, and the sixth column has the region id or "categoryid Make sure the script is using pandas and or numpy to read in the values as whole numbers without any decimals at all and it verifies there's no decimals being added in or read in from the csv file. Try the script out with a csv file with some integers in columns to make sure the script works as described above.
Here's the code I have so far and it gave me the error of "error converting row : invalid literal for int with base :
and in the csv file the value is just without the added decimal.
code:
import pandas as pd
import json
from pathlib import Path
def convertcsvtojsoncsvfilepath, jsonfilepath:
# Ensure the input and output file paths are Path objects
csvfilepath Pathcsvfilepath
jsonfilepath Pathjsonfilepath
# Check if the CSV file exists
if not csvfilepath.isfile:
printfError: The file csvfilepath does not exist!"
return
# Initialize lists for images and annotations
images
annotations
imageidmap # To track and assign unique IDs to each image
imageidcounter # Counter for image IDs
# Read the CSV file using pandas
try:
df pdreadcsvcsvfilepath, dtypestr # Read all columns as strings
except Exception as e:
printfError reading CSV file: e
return
for index, row in dfiterrows:
# Ensure that each row has the expected number of columns
if lenrow:
printfWarning: Row index does not have enough columns. Skipping..."
continue # Optionally skip rows with insufficient columns
# Extract data from the DataFrame row
filename rowstrip # File name as string
# Initialize variables
bboxx bboxy imagewidth imageheight categoryid None
# Extract integer values from the row, converting strings to integers
try:
# Remove any decimal points and convert to int
bboxx intfloatrowstripreplace # Bounding box X
bboxy intfloatrowstripreplace # Bounding box Y
imagewidth intfloatrowstripreplace # Image width
imageheight intfloatrowstripreplace # Image height
categoryid intfloatrowstripreplace # Category ID
except ValueError as e:
printfError converting row index: e Assigning default values for bbox
bboxx bboxy
imagewidth imageheight
categoryid # Assign a default category ID
# Check if the image is already added; if not, add it to the images list
if filename not in imageidmap:
imageentry
"filename": filename,
"height": imageheight,
"width": imagewidth,
id: imageidcounter
images.appendimageentry
imageidmapfilename imageidcounter
imageidcounter
# Get the imageid for this image
imageid imageidmapfilename
# Create entry for the bounding box annotation
annotationentry
"imageid: imageid
"bbox": bboxx bboxy bboxx imagewidth, bboxy imageheight
"categoryid: categoryid
annotations.appendannotationentry
# Combine images and annotations into the final dictionary
outputdict
"images": images,
"annotations": annotations
# Write the output dictionary to the JSON file
with jsonfilepath.openmodew as f:
json.dumpoutputdict, f indent
printfSuccessfully converted csvfilepath to jsonfilepath
# Specify your input and output file paths here
csvpath C:pathtoyourannotationscsv # Change this to your CSV file path
jsonpath C:pathtoyouroutputjson" # Change this to your desired JSON file path
# Run the conversion function
convertcsvtojsoncsvpath, jsonpath
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
