Skip to content

Commit bf73042

Browse files
author
Gabriel Ing
committed
Added arguments parsing, tested with range of images, fixed bugs with micron symbol by using pillow to add text, corrected scalebar length
1 parent 526b6a9 commit bf73042

1 file changed

Lines changed: 68 additions & 24 deletions

File tree

Image-previews_Opencv.py

Lines changed: 68 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,22 @@
33
import os
44
import matplotlib.pyplot as plt
55
import numpy as np
6+
from PIL import Image, ImageOps, ImageFont, ImageDraw, ImageFilter
7+
import time
8+
import argparse
9+
10+
parser = argparse.ArgumentParser(description='add additional arguments here')
11+
parser.add_argument('--file', help='if you only want one file processed, add this argment followed by the file')
12+
parser.add_argument('--color', help='If you want to specify the color of the scalebar, use this', default=None)
13+
parser.add_argument('--xybin', help='Default is to bin the image on xy by 2, if you want to change this, use this flag + integer', default=2, type=int)
14+
parser.add_argument('--textoff', help='if you dont want the text, use this followed by any integer', default=0)
15+
parser.add_argument('--quality', help='Default jpg quality is 80%, use this flag follwed by an integer to change this',default=80, type=int)
16+
args = parser.parse_args()
617

718

819
print('Dependancies imported')
920

10-
def Generate_preview_dm3(dm3_file, color='', textoff=False):
21+
def Generate_preview_dm3(dm3_file, color='', textoff=0, xybin=2, quality=80):
1122
#make a folder called previews to save the folder
1223
foldername = 'previews'
1324
if foldername not in os.listdir('.'):
@@ -27,22 +38,22 @@ def Generate_preview_dm3(dm3_file, color='', textoff=False):
2738
#of the image to bottom left of the scalebar - change this by editing /20 and /7.5 values (this just looked good to me)
2839

2940
scalebar_y = y-int(image.shape[0]/20)
30-
scalebar_x = x-int(image.shape[1]/7.5)
41+
scalebar_x = x-int(image.shape[1]/6)
3142

3243

3344
#Save pixel size
3445
pixelSize=dm3_input['pixelSize'][0]
35-
46+
pixelUnit = dm3_input['pixelUnit'][0]
3647
#possible scalebar sizes are given here, if its >500nm it should be in unit micron, hopefully this should only fail with very extreme examples
37-
possible_sizes = [1,2,5,10,25,50,100,250,500]
48+
possible_sizes = [0.5, 1,2,5,10,25,50,100,250,500]
3849

3950

4051
#to select sizes, iterate through possible sizes, if the width of the resulting scalebar (n*pixelsize)
4152
#is over 15% of the image size, the size is chose, if none are over 15% of image size
4253
#the largest size is chosen as default
4354

4455
for n in possible_sizes:
45-
width = n*pixelSize
56+
width = n*(1/pixelSize)
4657
#print(n, image.shape([0]/10)
4758
if width>(x/15):
4859
break
@@ -54,7 +65,7 @@ def Generate_preview_dm3(dm3_file, color='', textoff=False):
5465

5566
#apply median filter and gaussian blur
5667
img_median = cv.medianBlur(image,5)
57-
img_gauss = cv.GaussianBlur(img_median, (3,3),0)
68+
#img_gauss = cv.GaussianBlur(img_median, (3,3),0)
5869

5970
#Scale image between 0-255 (turn it into an 8bit greyscale image)
6071

@@ -67,52 +78,85 @@ def Generate_preview_dm3(dm3_file, color='', textoff=False):
6778
#choose color - this can be given as black, white or grey in the function
6879
if color=='black':
6980
pixvalue = 0
70-
textcolor = (0,0,0)
81+
textcolor = 'black'
7182
elif color=='white':
7283
pixvalue = 255
73-
textcolor=(255,255,255)
84+
textcolor='white'
7485
elif color=='grey':
7586
pixvalue = 150
76-
textcolor=(150,150,150)
87+
textcolor='grey'
7788
else: #default is black, unless it is a particularly dark area - if the mean pixvalue of the scale bar region is significantly less than the overall image mean, the scalebar will be white
7889

7990
if np.mean(new_arr[scalebar_y:scalebar_y+height,scalebar_x:scalebar_x+width])<np.mean(new_arr)/1.5:
8091
pixvalue = 255
81-
textcolor=(255,255,255)
92+
textcolor='white'
8293
else:
8394
pixvalue = 0
84-
textcolor = (0,0,0)
95+
textcolor = 'black'
8596
#add scalebar (set pixels to color)
8697

98+
99+
87100
new_arr[scalebar_y:scalebar_y+height,scalebar_x:scalebar_x+width]=pixvalue
88-
101+
#Bin image to reduce filesize, comment out if you want full image size
102+
new_arr = cv.resize(new_arr, (int(new_arr.shape[0]/xybin), int(new_arr.shape[1]/xybin)), interpolation=cv.INTER_CUBIC)
103+
104+
textposition = ((scalebar_x+width/2)/xybin,scalebar_y/xybin +20)
89105
#add label
90-
if textoff==False:
91-
font= cv.FONT_HERSHEY_DUPLEX #can change to any opencv fonts, they're all quite rubbish
92-
fontsize = image.shape[0]/1200 #this fontsize looks good to me
106+
107+
if pixelUnit!='nm':
108+
#print('yes')
109+
Utext = str(n)+u'\u00b5'+ 'm'
110+
text = str(n)+'microns'
111+
else:
112+
#print('no')
93113
text = '{}{}'.format(n,dm3_input['pixelUnit'][0])
94-
cv.putText(new_arr, text, (scalebar_x+3,scalebar_y-int(height*3/5)),font,fontsize, color=textcolor, thickness=int(fontsize*2.5))#can change thickness, color and position here
114+
Utext= text
115+
newname = foldername+'/'+dm3_file.strip('.dm3')+'_'+text+'scale.jpg'
116+
pil_image = Image.fromarray(new_arr)
95117

118+
if textoff==0:
119+
draw = ImageDraw.Draw(pil_image)
120+
121+
fontsize=int(x/(40*xybin))
122+
font = ImageFont.truetype("/Library/fonts/Arial.ttf", fontsize)
123+
draw.text(textposition, Utext, anchor ='rm', fill=textcolor, font=font, stroke_width=1)
124+
125+
pil_image.save(newname, quality=quality)
96126

97127

98128

99129

100-
#Bin image to reduce filesize, comment out if you want full image size
101-
new_arr = cv.resize(new_arr, (int(new_arr.shape[0]/2), int(new_arr.shape[1]/2)), interpolation=cv.INTER_CUBIC)
130+
131+
102132
#if you want to see it as it runs, can plot images heere
103133
#plt.gray()
104134
#plt.figure(figsize=(20,20))
105135
#plt.imshow(new_arr)
106136
#plt.show()
107137

108138
#create filename(and path)
109-
newname = foldername+'/'+dm3_file.strip('.dm3')+'{}{}'.format(n,dm3_input['pixelUnit'][0])+'scale.jpg'
110-
status = cv.imwrite(newname, new_arr,[int(cv.IMWRITE_JPEG_QUALITY), 70])
111-
print(newname, 'saved?: ',status)
139+
140+
#status = cv.imwrite(newname, new_arr,[int(cv.IMWRITE_JPEG_QUALITY), 70])
141+
print(newname, 'Done!')
112142

113143
#collect the dm3 files in the folder and make a preview for them all
114144

115-
dm3_files = [x for x in os.listdir('.') if x[-3:]=='dm3']
116-
for file in dm3_files:
117-
Generate_preview_dm3(file)
118145

146+
147+
start_time = time.time()
148+
if args.file==None:
149+
dm3_files = [x for x in os.listdir('.') if x[-3:]=='dm3']
150+
151+
for file in dm3_files:
152+
# if you have a scalebar color preference (black, white or grey) add it here, also turn off text by replacing false with True or ''
153+
Generate_preview_dm3(file, color=args.color, textoff=args.textoff,xybin=args.xybin,quality=args.quality)
154+
running_time = (time.time() - start_time)
155+
print("--- {} seconds ---".format(running_time))
156+
print('---{} seconds per file ---'.format(str(running_time/len(dm3_files))))
157+
else:
158+
Generate_preview_dm3(args.file, color=args.color, textoff=args.textoff,xybin=args.xybin,quality=args.quality)
159+
160+
running_time = (time.time() - start_time)
161+
print("--- {} seconds ---".format(running_time))
162+
#print(len(dm3_file))

0 commit comments

Comments
 (0)