reading-analog-gauge / make-dataset.py
2up1down's picture
Upload 2 files
de9a9d0 verified
raw
history blame
No virus
3.06 kB
# 1.unzip file
# 2. change *srcdir*
# 3. run this script
# do training
import numpy as np
from pathlib import Path
import os
outdir = "datasets/data/"
# setwhich one
# srcdir = "corners"
# srcdir = "keypoints"
if srcdir=="keypoints":
_KEYS = "start_kp center end_kp tip".split()
DIM = 640
elif srcdir=="corners":
_KEYS = "topLeft topRight bottomRight bottomLeft".split()
DIM = 1280
F = os.listdir(srcdir)
import random
random.seed(4)
random.shuffle(F)
F[0]
# 80% training
n = int(0.8*len(F))
n
train,val = F[:n], F[n:]
import shutil
for d in "images labels".split():
for dd in "train val test".split():
if not os.path.exists(f"{outdir}/{d}/{dd}"):
os.makedirs(f"{outdir}/{d}/{dd}")
for trgd,F in [(f"{outdir}/images/train", train), (f"{outdir}/images/val", val), (f"{outdir}/images/test", val[:100])]:
for srcf in F:
shutil.move(os.path.join(srcdir, srcf), os.path.join(trgd, srcf))
def filename2keypoints(fn:str):
kp = {}
i = 0
for sfn in fn.split("_"):
if "-" in sfn:
a,b = sfn.split("-")
kp[_KEYS[i]] = (int(a),int(b))
i+=1
return kp
# <class-index> <x> <y> <width> <height> <px1> <py1> <px2> <py2> ... <pxn> <pyn>
def formatLabel(cx,cy, w,h, kp):
pxs =""
for k in _KEYS:
x,y = kp[k]
pxs += f"{x/DIM} {y/DIM} "
return f"0 {cx/DIM} {cy/DIM} {w/DIM} {h/DIM} " +pxs.strip()
if srcdir=="keypoints":
def toCenterCoordinates(kp,dim = DIM):
# trying to determine bounding box via cv isnt reliable so we assume, dial face will always appears nearly same dim. and determine box from center point
w, h = 560,560
x,y = kp["center"]
wh = w/2
hh = h/2
cx = x-wh
cy = y - hh # left top corner
cx,cy, x,y
_w,_h = 0,0
# though this is not really correct, we will adjust dim. if bounding box is outside viewport
if cx<0:
_w = cx
elif x+wh > dim:
_w = (x+wh) - dim
if cy < 0:
_h = cy
elif (y+hh)>dim:
_h = (y+hh) - dim
return x,y, w-_w,h-_h
else:
def toCenterCoordinates(kp,dim = DIM):
# bounding corners
c = np.array(list(kp.values()))
margin = 10
topLeft,bottomRight = c.min(axis=0)-margin, c.max(axis=0)+margin
topLeft,bottomRight = np.clip(topLeft, 0, dim),np.clip(bottomRight, 0, dim)
cx,cy = 0.5*(bottomRight + topLeft)
w,h = bottomRight-topLeft
return cx,cy, w,h
# make annotation file
for d,F in [(f"{outdir}/images/train", train), (f"{outdir}/images/val", val), (f"{outdir}/images/test", val[:100])]:
for f in F:
_,ext = os.path.splitext(f)
antfn = os.path.join(outdir, d.replace("images/", "labels/"), _+".txt")
kp = filename2keypoints(f)
cx,cy,w,h = toCenterCoordinates(kp)
assert cx>0
assert cy>0
L = formatLabel(cx,cy,w,h, kp)
with open(antfn, "w") as fn:
fn.write(L+"\n")