Exemplo n.º 1
0
def makeDir(imFolder, outFolder, labelFile, dirFile, classRef, res=(300, 300)):
    coords, imNames, classes = get_labels(labelFile)
    print('Got labels')
    imFiles = listdir(imFolder)
    with open(dirFile, 'w') as outFile:
        for im in imFiles:
            if im.endswith('.tif'):
                arr = np.array(Image.open(path.join(imFolder, im)))
                chips, boxes, boxClasses = chip_image(arr,
                                                      coords[imNames == im],
                                                      classes[imNames == im],
                                                      res)

                for i in range(len(chips)):
                    chip = Image.fromarray(chips[i])
                    newName = path.join(outFolder,
                                        "{}_{}.jpg".format(im[:-4], i))
                    chip.save(newName)
                    boxStr = []
                    emptyChip = False
                    for j in range(len(boxes[i])):
                        box = boxes[i][j]
                        boxClass = boxClasses[i][j]
                        if boxClass == 0:
                            emptyChip = True
                        classID = getRealID(int(boxClasses[i][j]), classRef)
                        boxStr.append("{},{},{},{},{}".format(
                            int(box[0]), int(box[1]), int(box[2]), int(box[3]),
                            classID))
                    if not emptyChip:
                        infoStr = '{} {}\n'.format(newName, " ".join(boxStr))
                        outFile.write(infoStr)
                    # print(newName)

            print(im)
Exemplo n.º 2
0
def chip_one_image(src, json_file):

    img = Image.open(src)
    arr = np.array(img)
    coords, classes = get_labels_for_chip(src, json_file)
    c_img, c_box, c_cls = wv.chip_image(img=arr, coords=coords, classes=classes, shape=(416, 416))
    return c_img, c_box, c_cls
Exemplo n.º 3
0
    print(sd, flag1, flag2)

    trn_path = Path(args.output) / 'chip_train/'
    val_path = Path(args.output) / 'chip_valid/'
    trn_path.mkdir(parents=True, exist_ok=True)
    val_path.mkdir(parents=True, exist_ok=True)
    resolution = [args.resolution]  #416 # 672

    ## Train
    out_path = trn_path
    for idx in tqdm(idx_np[:trn_sz]):
        fname = idx2fname[idx]
        arr = wv.get_image(fname)
        for res in resolution:
            im, box, classes_final = wv.chip_image(
                arr, coords[img_fn == fname.name],
                classes[img_fn == fname.name], (res, res))
            for idx, (x, b, c) in enumerate(
                    zip(im, box.values(), classes_final.values())):
                if len(c) == 1 and c[0] == 0: continue  ## no instance
                else:
                    im_data = Image.fromarray(x)
                    tmp_fn = '_'.join(map(str, [fname.stem, idx, res]))
                    im_data.save(out_path / (tmp_fn + '.jpg'))
                    with open(str(out_path / (tmp_fn + '.txt')),
                              'w') as anno_f:
                        yolob = convert_to_yolo_box(x.shape[:2], b)
                        for i in range(len(c)):
                            anno_f.write(
                                str(idremap[int(c[i])]) + ' ' +
                                ' '.join(map(str, yolob[i])) + '\n')
Exemplo n.º 4
0
with open('xview_class_labels.txt') as f:
    for row in csv.reader(f):
        labels[int(row[0].split(":")[0])] = row[0].split(":")[1]
        pass
    pass

i = 0
for chip_name in tqdm.tqdm(all_images[:300]):
    chip_name = (chip_name.split("/")[-1])
    img_name = chip_name.split(".")[0]

    coords = coords1[chips1 == chip_name]
    classes = classes1[chips1 == chip_name].astype(np.int64)

    c_img, c_box, c_cls = wv.chip_image(img=arr,
                                        coords=coords,
                                        classes=classes,
                                        shape=(600, 600))
    # xmin,ymin,xmax,ymax = c_box
    #   0    1   2    3
    for c_idx in (range(c_img.shape[0])):
        # Save the chipped image
        c_name = "{:06}_{:02}".format(int(img_name), c_idx)
        # Save the chipped label
        widths = c_box[c_idx][:, 2] - c_box[c_idx][:, 0]
        x = c_box[c_idx][:, 0] + (widths / 2)

        heights = c_box[c_idx][:, 3] - c_box[c_idx][:, 1]
        y = c_box[c_idx][:, 1] + (heights / 2)

        szx = c_img[c_idx].shape[0]
        szy = c_img[c_idx].shape[1]
Exemplo n.º 5
0
print(thechips[0])
print(theclasses[0])

#yo = chip_image('2355.tif', thecoords[0], theclasses[0])
chip_name = '104.tif'
arr = wv.get_image(chip_name)

plt.figure(figsize=(10,10))
plt.axis('off')
plt.imshow(arr)
print('\nyo\n')




c_img, c_box, c_cls = wv.chip_image(img = arr, coords=thecoords, classes=theclasses, shape=(1000,1000))
print("Num Chips: %d" % c_img.shape[0])

print("\nnumber of chips : ", c_img.shape[0])

w = c_img.shape[0]

#We can plot some of the chips
fig,ax = plt.subplots(3)
fig.set_figheight(5)
fig.set_figwidth(5)

for k in range(9):
    plt.subplot(3,3,k+1)
    plt.axis('off')
    plt.imshow(c_img[np.random.choice(range(c_img.shape[0]))])
Exemplo n.º 6
0
all_coords, all_chips, all_classes = wv.get_labels(OLD_ROOT +
                                                   "/xView_train.geojson")

max_gt_boxes = 0

# Iterate over each tif, and chip
for e, tif in enumerate(tif_list):
    print("{} / {}".format(e, len(tif_list)))
    # Get the info relevant to this single full frame .tif
    ff_coords = all_coords[all_chips == tif]
    ff_classes = all_classes[all_chips == tif].astype(np.int64)

    # Chip the image into smaller pieces
    arr = wv.get_image(OLD_ROOT + "/train_images/" + tif)
    c_img, c_box, c_cls = wv.chip_image(img=arr,
                                        coords=ff_coords,
                                        classes=ff_classes,
                                        shape=chip_shape)
    num_chips = len(c_img)

    # Iterate over chips for this tif
    for i in range(num_chips):
        # If chip has no gt boxes, skip
        if len(c_box[i]) == 1 and c_box[i].all() == 0:
            continue
        if len(c_box[i]) > max_gt_boxes:
            max_gt_boxes = len(c_box[i])
            max_gt_chip_num = i
            max_gt_tif = tif
            print("new best:", max_gt_boxes, max_gt_tif, max_gt_chip_num)

print("max_gt_boxes:", max_gt_boxes)
Exemplo n.º 7
0
    xyz += 1
    print("Working on: [{} / {}] {} ".format(xyz, len(tif_names), unique_tif))

    # Make sure the file exists
    if not os.path.isfile(OLD_ROOT + "/train_images/" + unique_tif):
        continue

    # Get the info relevant to this single full frame .tif
    ff_coords = all_coords[all_chips == unique_tif]
    ff_classes = all_classes[all_chips == unique_tif].astype(np.int64)
    print("\tTotal Num Targets: ", len(ff_classes))

    # Chip the image into smaller pieces
    arr = wv.get_image(OLD_ROOT + "/train_images/" + unique_tif)
    c_img, c_box, c_cls = wv.chip_image(img=arr,
                                        coords=ff_coords,
                                        classes=ff_classes,
                                        shape=CHIP_SHAPE)
    num_chips = len(c_img)
    print("\tNum Chips: ", num_chips)

    # For each image chip (i in range(num_chips))
    for i in range(num_chips):

        print("\t\tChip #: ", i)
        print("\t\t\tNum Targets in Chip: ", len(c_cls[i]))
        #print c_cls[i]
        #print c_box[i]

        # Git rid of very small boxes that are artifacts of chipping
        final_boxes = []
        final_classes = []
Exemplo n.º 8
0
    # Make sure the file exists
    if not os.path.isfile(OLD_ROOT + "/train_images/" + unique_tif):
        continue

    # Get the info relevant to this single full frame .tif
    ff_coords = all_coords[all_chips == unique_tif]
    ff_classes = all_classes[all_chips == unique_tif].astype(np.int64)
    #print("\tTotal Num Targets: ",len(ff_classes))

    # Add multiscale loop
    for scale in CHIP_SHAPE:

        # Chip the image into smaller pieces
        arr = wv.get_image(OLD_ROOT + "/train_images/" + unique_tif)
        c_img, c_box, c_cls = wv.chip_image(img=arr,
                                            coords=ff_coords,
                                            classes=ff_classes,
                                            shape=(scale, scale))
        num_chips = len(c_img)
        #print("\tNum Chips: ",num_chips)

        # For each image chip (i in range(num_chips))
        for i in range(num_chips):

            #print("\t\tChip #: ",i)

            # Calculate the center of the chip
            center = (int(c_img[i].shape[0] / 2), int(c_img[i].shape[1] / 2))

            # For each of the desired rotation degrees
            for val in range(0, 360, 10):