Skip to content

Instantly share code, notes, and snippets.

@Attila94
Created May 30, 2019 05:56
Show Gist options
  • Save Attila94/80f48b12abdb3cb9eed2f3a54f7e9cf5 to your computer and use it in GitHub Desktop.
Save Attila94/80f48b12abdb3cb9eed2f3a54f7e9cf5 to your computer and use it in GitHub Desktop.
Make 96*96 square crops from bounding boxes of ExDark dataset.
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 14:33:10 2019
Make 96*96 square crops from bounding boxes of ExDark dataset.
@author: Attila Lengyel
"""
import numpy as np
import os, cv2
inpath = r'C:\Projects\MSc Thesis\data\ExDark - Copy\input'
lblpath = r'C:\Projects\MSc Thesis\data\ExDark - Copy\ExDark_Annno'
outpath = r'C:\Projects\MSc Thesis\data\ExDark - Copy\output'
categories = next(os.walk(inpath))[1]
for cat in categories: # Loop through categories
catpath = os.path.join(inpath,cat)
im_files = next(os.walk(catpath))[2]
for im_file in im_files: # Loop through images in category
im_path = os.path.join(catpath,im_file)
lbl_path = os.path.join(lblpath,cat,im_file+'.txt')
# Read label file corresponding to image
with open(lbl_path, 'r') as lblfile:
lbls = lblfile.readlines()
for lbl in lbls:
im = cv2.imread(im_path,cv2.IMREAD_COLOR)[:,:,::-1] # load image
lbl = lbl.split()
# Calculate crop coordinates if categories correspond
if lbl[0].lower() == cat.lower():
x,y,w,h = list(map(int,lbl[1:5]))
if w<h:
dif = int((h-w)/2)
x -= dif
w += dif*2
elif w>h:
dif = int((w-h)/2)
y -= dif
h += dif*2
# Check if crop is not out of bounds
if x < 0:
appim = np.zeros((im.shape[0],dif,3))
im = np.hstack((appim,im,appim))
x = 0
if y < 0:
appim = np.zeros((dif,im.shape[1],3))
im = np.vstack((appim,im,appim))
y = 0
im = im[y:y+h,x:x+w] # Crop image
if (w >= 96 and h >= 96): # Resize image if too large
im = cv2.resize(im,(96,96))
# Save image (only if large enough)
imoutpath = os.path.join(outpath,cat,im_file)
print(imoutpath)
cv2.imwrite(imoutpath,im[:,:,::-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment