Skip to content

Commit ead246c

Browse files
committed
added pre and post processing scripts for testing on Milton
1 parent 7e4e689 commit ead246c

4 files changed

Lines changed: 194 additions & 4 deletions

File tree

partinet/__init__.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,24 @@ def main():
5858
pass
5959

6060
@main.command()
61-
def preprocess():
62-
click.echo("This will preprocess the micrographs.")
63-
raise NotImplementedError("Not implemented yet!")
61+
@click.option("--labels", required=True, help="Path to the labels directory")
62+
@click.option("--images", required=True, help="Path to the images directory")
63+
@click.option("--output", required=True, help="Path to the output directory")
64+
def preprocess(labels, images, output):
65+
click.echo("Preprocessing the micrographs...")
66+
import partinet.split_train
67+
partinet.split_train.main(labels, images, output)
68+
69+
@main.command()
70+
@click.option("--labels", required=True, help="Path to the labels directory")
71+
@click.option("--images", required=True, help="Path to the images directory")
72+
@click.option("--output", required=True, help="Path to the output STAR file")
73+
@click.option("--conf", default=0.0, help="Minimum confidence threshold from predictions")
74+
def star(labels, images, output,conf):
75+
click.echo("Generating STAR file...")
76+
import partinet.star_file
77+
partinet.star_file.main(labels,images,output,conf)
78+
6479

6580
@main.group()
6681
def train():

partinet/split_train.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import os
2+
import shutil
3+
import argparse
4+
5+
import numpy as np
6+
from sklearn.model_selection import train_test_split as tts
7+
8+
def main(labels_path, images_path, output_dir):
9+
if not os.path.exists(output_dir):
10+
os.makedirs(output_dir)
11+
os.makedirs(os.path.join(output_dir, "images"))
12+
os.makedirs(os.path.join(output_dir, "labels"))
13+
os.makedirs(os.path.join(output_dir, "images", "train"))
14+
os.makedirs(os.path.join(output_dir, "images", "val"))
15+
os.makedirs(os.path.join(output_dir, "labels", "train"))
16+
os.makedirs(os.path.join(output_dir, "labels", "val"))
17+
18+
files = os.listdir(labels_path)
19+
# splitting data into training and val
20+
train_idx, val_idx = tts(np.arange(0, len(files), 1), shuffle=True)
21+
22+
for idx, file in enumerate(files):
23+
file_name = file[:-4]
24+
if idx in train_idx:
25+
# copying train images
26+
shutil.copy(os.path.join(images_path, file_name+".jpg"), os.path.join(output_dir, "images", "train", file_name+".jpg"))
27+
28+
# copying train labels
29+
shutil.copy(os.path.join(labels_path, file_name+".txt"), os.path.join(output_dir, "labels", "train", file_name+".txt"))
30+
31+
elif idx in val_idx:
32+
# copying val images
33+
shutil.copy(os.path.join(images_path, file_name+".jpg"), os.path.join(output_dir, "images", "val", file_name+".jpg"))
34+
35+
# copying val labels
36+
shutil.copy(os.path.join(labels_path, file_name+".txt"), os.path.join(output_dir, "labels", "val", file_name+".txt"))
37+
38+
# creating val.txt file
39+
with open(os.path.join(output_dir, "val.txt"), "w") as f:
40+
for file in os.listdir(os.path.join(output_dir, "images", "val")):
41+
f.write(str(os.path.join(output_dir, "images", "val", file))+"\n")
42+
43+
# creating train.txt file
44+
with open(os.path.join(output_dir, "train.txt"), "w") as f:
45+
for file in os.listdir(os.path.join(output_dir, "images", "train")):
46+
f.write(str(os.path.join(output_dir, "images", "train", file))+"\n")
47+
48+
# creating cryo_training.yaml file
49+
to_write = f"""train: {os.path.join(output_dir, "train.txt")}
50+
val: {os.path.join(output_dir, "val.txt")}
51+
52+
# number of classes
53+
nc: 1
54+
55+
# class names
56+
names: [ 'particle' ]"""
57+
58+
with open(os.path.join(output_dir, "cryo_training.yaml"), "w") as f:
59+
f.write(to_write)
60+
61+
def parse_args():
62+
parser = argparse.ArgumentParser(description="Create training data split from images and labels.")
63+
parser.add_argument("--labels", required=True, help="Path to the labels directory")
64+
parser.add_argument("--images", required=True, help="Path to the images directory")
65+
parser.add_argument("--output", required=True, help="Path to the output directory")
66+
67+
return parser.parse_args()
68+
69+
if __name__ == "__main__":
70+
args = parse_args()
71+
main(args.labels, args.images, args.output)

partinet/star_file.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import math
2+
import os
3+
4+
import pandas as pd
5+
import csv
6+
import cv2
7+
import argparse
8+
9+
def yolo_to_starfile(yolo_coords, image_width, image_height,diameters):
10+
x_center = math.ceil(yolo_coords['x_centre'] * image_width)
11+
y_center = math.ceil(yolo_coords['y_centre'] * image_height)
12+
width = yolo_coords['width'] * image_width
13+
height = yolo_coords['height'] * image_height
14+
15+
# Calculate diameter
16+
diameter = math.ceil(max(width, height))
17+
18+
diameters.append(diameter)
19+
20+
# Return x_center, y_center, diameter
21+
return x_center, y_center, diameter
22+
23+
24+
# Modify the generate_output function to accept DynamicDet DataFrame
25+
def generate_output(labels, filename, star_writer,diameters,img_width,img_height):
26+
for index, row in labels.iterrows():
27+
# x_centre = row['X-Coordinate']
28+
# y_centre = row['Y-Coordinate']
29+
# diameter = row['Diameter']
30+
31+
x_centre, y_centre, diameter = yolo_to_starfile(row, img_width, img_height,diameters)
32+
# print(x_centre, y_centre, diameter)
33+
34+
star_writer.writerow([filename, x_centre, y_centre, diameter])
35+
36+
def main(labels_path,images_path,star_out_path,conf_thresh):
37+
# # Read DynamicDet output from txt file
38+
# labels_path = "path/to/labels"
39+
# images_path = "path/to/denoised_images"
40+
# star_out_path = "output/path/file.star"
41+
# conf_thresh = 0.5
42+
43+
diameters = list()
44+
45+
with open(star_out_path, "w") as star_file:
46+
star_writer = csv.writer(star_file, delimiter=' ')
47+
star_writer.writerow([])
48+
star_writer.writerow(["data_"])
49+
star_writer.writerow([])
50+
star_writer.writerow(["loop_"])
51+
star_writer.writerow(["_rlnMicrographName", "#1"])
52+
star_writer.writerow(["_rlnCoordinateX", "#2"])
53+
star_writer.writerow(["_rlnCoordinateY", "#3"])
54+
star_writer.writerow(["_rlnDiameter", "#4"])
55+
56+
i = 1
57+
for image in os.listdir(images_path):
58+
filename = image.split("/")[-1][:-4]
59+
60+
print(i)
61+
62+
i+=1
63+
64+
label_file_path = os.path.join(labels_path, str(filename + '.txt'))
65+
66+
if not os.path.exists(label_file_path):
67+
continue
68+
69+
# label_file_path = os.path.join(labels_path, str(filename + '.csv'))
70+
# labels = pd.read_csv(label_file_path)
71+
72+
image = cv2.imread(os.path.join(images_path, image))
73+
img_width = image.shape[1]
74+
img_height = image.shape[0]
75+
76+
77+
custom_headers = ['class', 'x_centre', 'y_centre', 'width', 'height', 'conf']
78+
79+
# Read the CSV file with custom headers
80+
labels = pd.read_csv(label_file_path, header=None, names=custom_headers, sep=' ')
81+
82+
labels = labels[labels['conf'] > conf_thresh]
83+
84+
# print(labels.head())
85+
86+
# label_file_path = os.path.join(labels_path, str(filename + '.csv'))
87+
# labels = pd.read_csv(label_file_path)
88+
89+
star_filename = str(filename + '.mrc')
90+
91+
generate_output(labels, star_filename, star_writer,diameters,img_width,img_height)
92+
93+
def parse_args():
94+
parser = argparse.ArgumentParser(description="Generate STAR file from PartiNet predictions")
95+
parser.add_argument("--labels", required=True, help="Path to the labels directory")
96+
parser.add_argument("--images", required=True, help="Path to the images directory")
97+
parser.add_argument("--output", required=True, help="Path to the output STAR file")
98+
parser.add_argument("--conf", required=True, help="Minimum confidence threshold for predictions")
99+
100+
return parser.parse_args()
101+
102+
if __name__ == "__main__":
103+
args = parse_args()
104+
main(args.labels, args.images, args.output, args.conf)

0 commit comments

Comments
 (0)