Created
May 19, 2022 18:09
-
-
Save iaverypadberg/6644c77afadb9696e78c0dcbec2b16cd to your computer and use it in GitHub Desktop.
Changes the scales down the image size and the corresponding bounding box.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from re import S | |
import xml.etree.ElementTree as ET | |
from glob import glob | |
import cv2 | |
input_dir ='/home/isaac/Desktop/work_area/working_on/' | |
files = glob(input_dir+'*.png') | |
# For each file with a .png extension | |
for file in files: | |
scale_factor = random.randint(3,8) | |
scale_factor = scale_factor/10 | |
print(scale_factor) | |
# -------- PNG WORK -------- # | |
img = cv2.imread(file,1) | |
cv2.imshow('Original', img) | |
# Scale the image by half | |
img_half = cv2.resize(img, (0, 0), fx=scale_factor, fy=scale_factor) | |
# Collect the scaled image dimensions | |
x_dim = img_half.shape[0] | |
y_dim = img_half.shape[1] | |
# Save the image to the directory where it originated | |
cv2.imwrite(file, img_half) | |
# ------- XML WORK -------- # | |
# Get the xml file name | |
tmp_file = file.split(".") | |
xml_file = tmp_file[0]+'.xml' | |
# Open the xml file | |
tree = ET.parse(xml_file) | |
root = tree.getroot() | |
bbox = root.find('object').find('bndbox') | |
# Access the bounding box coordinates | |
xmin = bbox.find('xmin') | |
ymin = bbox.find('ymin') | |
xmax = bbox.find('xmax') | |
ymax = bbox.find('ymax') | |
# Need to round down or up, cannot have half a pixel | |
# Change to a string for the xml | |
xmin.text = str(round(int(xmin.text)*scale_factor)) | |
ymin.text = str(round(int(ymin.text)*scale_factor)) | |
xmax.text = str(round(int(xmax.text)*scale_factor)) | |
ymax.text = str(round(int(ymax.text)*scale_factor)) | |
# Access the image dimensions | |
width = root.find('size').find('width') | |
height = root.find('size').find('height') | |
# Change the image dimensions in the xml file | |
width.text = str(x_dim) | |
height.text = str(y_dim) | |
# Save the changes to the xml file | |
tree.write(xml_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment