|
|
|
|
|
|
|
|
|
|
|
import numpy as np |
|
from pathlib import Path |
|
import os |
|
|
|
outdir = "datasets/data/" |
|
|
|
|
|
|
|
|
|
|
|
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] |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
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): |
|
|
|
w, h = 560,560 |
|
x,y = kp["center"] |
|
wh = w/2 |
|
hh = h/2 |
|
|
|
cx = x-wh |
|
cy = y - hh |
|
|
|
cx,cy, x,y |
|
_w,_h = 0,0 |
|
|
|
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): |
|
|
|
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 |
|
|
|
|
|
|
|
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") |