hi i want to read 8 numerical columns from some txt files for calculating average of these numbers.
indeed i want to make label files that are suitable for training Yolo V5 for an object detection task (using Google Earth Images)
i have some label files (for some images) that contain coordinates of 4 corners for bounding boxes around objects (instances) into my images.
i wrote below codes for reading these numbers (coordinates) from txt files and then i want to calculate average of x1,x2,x3 and x4 and average of y1,y2,y3 and y4 and calculate width and height for bounding boxes. finally normalize them (0 to 1).
from google.colab import drive
drive.mount('/content/drive')
file_path = ('/content/drive/MyDrive/labelfiles/P0002_ColabFormat.txt')
def read_bounding_boxes_from_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
bounding_boxes = []
for line in lines:
# Split each line into individual numbers
coordinates = [int(coord) for coord in line.strip().split()]
# Check if the line contains at least 8 coordinates (2 points)
if len(coordinates) >= 8:
# Reshape the coordinates into pairs of (x, y) tuples
bbox = [(coordinates[i], coordinates[i+1]) for i in range(0, len(coordinates), 2)]
bounding_boxes.append(bbox)
return bounding_boxes
def calculate_center_and_dimensions(bbox):
# Extract corner coordinates
# image P0002
image_width = 2557
image_height = 2086
x1, y1 = bbox[0] # Top-left corner
x2, y2 = bbox[1] # Top-right corner
x3, y3 = bbox[2] # Bottom-right corner
x4, y4 = bbox[3] # Bottom-left corner
# Calculate center coordinates
x_center = (x1 + x2 + x3 + x4) / 4
y_center = (y1 + y2 + y3 + y4) / 4
# Calculate width and height
width = max(x1, x2, x3, x4) - min(x1, x2, x3, x4)
height = max(y1, y2, y3, y4) - min(y1, y2, y3, y4)
x_center /= image_width
y_center /= image_height
width /= image_width
height /= image_height
return x_center, y_center, width, height
# Example usage
oriented_bbox = [bounding_boxes] # Example oriented bounding box coordinates
x_center, y_center, width, height = calculate_center_and_dimensions(oriented_bbox)
print("Center coordinates (x_center, y_center):", x_center, y_center)
print("Dimensions (width, height):", width, height)
but colab shows below error message:
ValueError Traceback (most recent call last)
in <cell line: 48>()
46 # Example usage
47 oriented_bbox = [bounding_boxes] # Example oriented bounding box coordinates
—> 48 x_center, y_center, width, height = calculate_center_and_dimensions(oriented_bbox)
49 print(“Center coordinates (x_center, y_center):”, x_center, y_center)
50 print(“Dimensions (width, height):”, width, height)
in calculate_center_and_dimensions(bbox)
20 image_width = 2557
21 image_height = 2086
—> 22 x1, y1 = bbox[0] # Top-left corner
23 x2, y2 = bbox[1] # Top-right corner
24 x3, y3 = bbox[2] # Bottom-right corner
ValueError: too many values to unpack (expected 2)