-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_tibia_femur_tiankuo.py
More file actions
197 lines (164 loc) · 7.1 KB
/
split_tibia_femur_tiankuo.py
File metadata and controls
197 lines (164 loc) · 7.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#! /home/spl/ml/sitk/bin/python
# -*- coding: utf-8 -*-
import os
import SimpleITK as sitk
from shubow_tools import *
import re
import time
import concurrent.futures
import logging
import cv2
import shutil
import glob
import matplotlib.pyplot as plt
import numpy as np
def knee_joint_z_index(limb, _min=1200, _max=2000, threshold=50): #100
'''
Description:
Given a 3D image of one limb, find the z_index of the knee where the largest contour
in this slice is the smallest among all 2D slices.
Args:
limb: ndarray, dimension = 3
return:
z_index: integer
'''
min_contour_size = float('inf')
smallest_largest_contour = None # Initialize to None or a suitable default
thresh_slice_image=None
knee_slice_index = -1
for i, slice in enumerate(limb):
#apply Median Blur
slice = cv2.GaussianBlur(slice, (5, 5), 0)
# Apply threshold
ret, thresh_slice = cv2.threshold(slice, threshold, 255, cv2.THRESH_BINARY)
# Define a kernel for morphological operations
kernel = np.ones((15, 15), np.uint8)
# Apply closing (dilation followed by erosion)
thresh_slice = cv2.morphologyEx(thresh_slice, cv2.MORPH_CLOSE, kernel)
# Find contours
contours, _ = cv2.findContours(thresh_slice.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
if _min<i<_max : #i == 1361:
# Find the contour with the largest perimeter
largest_contour = max(contours, key=lambda contour: cv2.arcLength(contour, True))
# Check if this is the smallest largest contour so far
if cv2.arcLength(largest_contour, True) < min_contour_size:
# Update the smallest largest contour perimeter found
min_contour_size = cv2.arcLength(largest_contour, True)
thresh_slice_image=thresh_slice
smallest_largest_contour = largest_contour
knee_slice_index = i
# # Convert contour_img to a 3-channel RGB image if it's a grayscale image
# if len(thresh_slice_image.shape) == 2:
# thresh_slice_image = cv2.cvtColor(thresh_slice_image, cv2.COLOR_GRAY2RGB)
# # Draw the largest contour
# cv2.drawContours(thresh_slice_image, [smallest_largest_contour], -1, (255, 0, 0), 3) # Red contour
# # Plotting
# print(knee_slice_index,cv2.contourArea(smallest_largest_contour) )
# plt.figure(figsize=(6, 6))
# plt.imshow(thresh_slice_image, cmap='gray')
# plt.title("smallest coutour among slices")
# plt.show()
return knee_slice_index
def LR_mid_x(image):
'''
Desription:
Given a 3D reconstruction, find the x_index to split left and right
Args:
limb: ndarray, dimension = 3
return:
center: ndarray,
'''
z_project = image.mean(axis = 0)
xy_dex = np.vstack(np.nonzero(z_project))
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) # kmeans parameters
k=2
attempts=15
ret, label, center = cv2.kmeans(np.float32(xy_dex.transpose()),k,
None,criteria,attempts,cv2.KMEANS_PP_CENTERS)
mid_x_index = int(center[:, 1].sum()/2)
return mid_x_index
def splitLRTF(folder,imgtitle,outfd = None):
logging.info("Reading {}".format(imgtitle))
img = imreadseq_multithread(folder, sitkimg= False, rmbckgrd=60, thread=2)
#logging.info("Processing...split LT & LF")
width = img.shape[2]
mid_idx = LR_mid_x(img)
if not outfd is None:
pass
else:
outfd = folder
pathlist = []
pathlist.append(os.path.join(outfd,imgtitle+' week 11 left tibia' ))
pathlist.append(os.path.join(outfd,imgtitle+' week 11 left femur' ))
pathlist.append(os.path.join(outfd,imgtitle+' week 11 right tibia'))
pathlist.append(os.path.join(outfd,imgtitle+' week 11 right femur'))
for fd in pathlist:
if os.path.exists(fd):
shutil.rmtree(fd)
os.mkdir(fd)
else:
os.mkdir(fd)
titlelist = [imgtitle+' week 11 left tibia', imgtitle+' week 11 left femur',
imgtitle+' week 11 right tibia',imgtitle+' week 11 right femur']
left = auto_crop(img[:,:,:mid_idx])
right = auto_crop(img[:,:,-1:mid_idx:-1])
del img
##### Save left tibia and femur #####
logging.info("Processing...split LT & LF")
z_index_splt_left=knee_joint_z_index(left)
left_tibia = sitk.GetImageFromArray(auto_crop(left[:z_index_splt_left]))
left_femur = sitk.GetImageFromArray(auto_crop(left[z_index_splt_left:]))
del left
# use multiple threads to accelerate writng images to disk.
# create an iterable to be passed to imreadseq(img,fd,title)
imagelist = [left_tibia,left_femur]
logging.info("Writing...")
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.map(imsaveseq,imagelist,pathlist[:2],titlelist[:2])
del left_tibia,left_femur
##### Save right tibia and femur #####
logging.info("Processing...split RT & RF")
z_index_splt_right=knee_joint_z_index(right)
right_tibia = sitk.GetImageFromArray(auto_crop(right[:z_index_splt_right]))
right_femur = sitk.GetImageFromArray(auto_crop(right[z_index_splt_right:]))
del right
imagelist = [right_tibia,right_femur]
logging.info("Writing...")
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.map(imsaveseq,imagelist,pathlist[2:],titlelist[2:])
del right_tibia,right_femur
if __name__ == "__main__":
masterfolder = r'F:\PD mice\PD mice 120823\recon\week 11'
masterout = r'F:\PD mice\PD mice 120823\seg\week 11 new'
if not os.path.exists(masterout):
os.mkdir(masterout)
time1 = time.time()
count = 0
'''
with open(r"/media/spl/D/MicroCT_data/Shubo/Reconstruction image/retry.txt", "r") as file:
retry = file.readlines()
retry = [i[:-1] for i in retry]
'''
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
failed = []
#for inputfd in glob.glob(os.path.join(masterfolder,"*reconstruction")):
for folder in sorted(os.listdir(masterfolder))[:]:
if folder [0:10] : # #if folder[0:10] in ["555 week 2_Rec"]: if folder[0:10]: #####################edit
count += 1
ID = os.path.basename(folder)[0:12]
logging.info('Cropping for {} started.'.format(ID))
try:
splitLRTF(os.path.join(masterfolder,folder),ID,masterout)
logging.info('Cropping for {} is completed.'.format(ID))
except Exception as err:
print(err)
failed.append(folder)
logging.exception('Cropping for {} failed.'.format(ID))
pass
print(failed)
time2 = time.time()
logging.info("Total time used: {: >8.1f} seconds".format(time2-time1))
logging.info("Average time used: {: >8.1f} seconds".format((time2-time1)/count))