Commit f462c104 authored by Saad Jbabdi's avatar Saad Jbabdi
Browse files

Updates including Paul's magic

parent 2465b150
#!/usr/bin/env python3
from PIL import Image
#!/usr/bin/env python
#from PIL import Image
import tifffile as tif
import numpy as np
import matplotlib.pyplot as plt
import os
......@@ -45,12 +46,12 @@ class CellPicker(object):
linestyle='None', markersize=5, color="red")
self.figure.canvas.draw()
def on_key_dunno(self, event):
if event.key == 'n':
plt.close()
plt.close()
def main():
# Parse command line arguments
......@@ -93,6 +94,7 @@ def main():
with open(outfile,'w') as f:
f.write('Sub-Image-File\tXcoord\tYcoord\n')
counter = 0
for file in files:
#First, get h and w values corresponding to sub-image from filename.
#This is in order to export x,y coordinates relative to original brain_slice image.
......@@ -107,8 +109,6 @@ def main():
#prepare figure and load .npy files in as an image, ready to show
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title("Click on cells. \n"
"'q'=quit, 'u'=undo, 'n'=dunno \nClose figure if you can't see any cells")
im = ax.imshow(np.load(file))
ax.set_xlim(ax.get_xlim())
......@@ -117,7 +117,13 @@ def main():
#Instantiate CellPicker class
p = CellPicker(fig,ax)
counter += 1
ax.set_title("Click on cells. \n"
"'q'=quit, 'u'=undo, 'n'=dunno \n"
"Close if you can't see any cells \n"
"Processed {}/{}".format(counter,len(files)))
#Once past this we move to the next image...
plt.show()
......
#!/usr/bin/env python3
#!/usr/bin/env python
from PIL import Image
#from PIL import Image
import matplotlib as mpl
mpl.use('macosx')
# mpl.use('macosx')
mpl.use('wxagg')
from matplotlib.widgets import RectangleSelector
from matplotlib.widgets import RectangleSelector, Slider
from matplotlib.image import AxesImage
import numpy as np
import os
import os.path as op
......@@ -14,44 +16,156 @@ import shutil
import matplotlib.pyplot as plt
import argparse
import sys
import time
# use this for BigTiff
import tifffile as tif
from skimage import io as skio
#Image.MAX_IMAGE_PIXELS = None
# pilfered from https://stackoverflow.com/a/19306776
def get_ax_size(fig, ax):
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
width *= fig.dpi
height *= fig.dpi
return width, height
Image.MAX_IMAGE_PIXELS = 5282426800
class ZoneSelector(object):
def __init__(self,ax,outbase,img,res):
def __init__(self,ax,outbase,img):
self.box = []
self.axis = ax
self.zone_number = 0
self.image = img
self.outbase = outbase
self.res = res
self.rs = RectangleSelector(self.axis,
self.select_callback,
drawtype='box',
rectprops = dict(facecolor='orange',
edgecolor = 'red', alpha=0.2, fill=True))
def select_callback(self, eclick, erelease):
print('down', eclick)
print('up ', erelease)
x1, y1 = eclick.xdata, eclick.ydata
x2, y2 = erelease.xdata, erelease.ydata
zone = np.array((np.min([x1,x2]),
np.min([y1,y2]),
np.max([x1,x2]),
np.max([y1,y2])))*self.res
crop = self.image.crop(zone)
crop.save(self.outbase + "_zone{:03d}.tiff".format(self.zone_number), "TIFF")
y1 = 1 - y1
y2 = 1 - y2
h, w = self.image.shape[:2]
zone = np.array((np.min([x1,x2]) * w,
np.min([y1,y2]) * h,
np.max([x1,x2]) * w,
np.max([y1,y2]) * h)).astype('i4')
x1, y1, x2, y2 = zone
crop = self.image[y1:y2, x1:x2, :]
tif.imsave(self.outbase + "_zone{:03d}.tiff".format(self.zone_number),crop)
#crop.save(self.outbase + "_zone{:03d}.tiff".format(self.zone_number), "TIFF")
with open(self.outbase + "_zone{:03d}.txt".format(self.zone_number),"w") as fcoord:
fcoord.write('{} {} {} {}'.format(*zone))
self.zone_number +=1
class BigImageViewer(object):
def __init__(self, fig, ax, data):
self.fig = fig
self.ax = ax
self.data = data
self.ax_img = None
ax.set_autoscale_on(False)
self.vmin_ax = fig.add_axes([0.2, 0.1, 0.6, 0.03])
self.vmax_ax = fig.add_axes([0.2, 0.05, 0.6, 0.03])
self.vmin_ctrl = Slider(self.vmin_ax, 'vmin', 0, 255, 0)
self.vmax_ctrl = Slider(self.vmax_ax, 'vmax', 0, 255, 255)
self.vmin_ctrl.on_changed(self.refresh)
self.vmax_ctrl.on_changed(self.refresh)
self.ax.callbacks.connect('xlim_changed', self.refresh)
self.ax.callbacks.connect('ylim_changed', self.refresh)
self.refresh()
def get_data(self, cw, ch, xmin, xmax, ymin, ymax):
dh, dw = self.data.shape[:2]
dws = xmin * dw
dwe = xmax * dw
dhs = (1 - ymin) * dh
dhe = (1 - ymax) * dh
dhs, dhe = sorted((dhs, dhe))
dwlen = dwe - dws
dhlen = dhe - dhs
ratew = max(1, int(float(dwlen) / cw))
rateh = max(1, int(float(dhlen) / ch))
dws, dwe = np.clip((dws, dwe), 0, dw).astype(np.int)
dhs, dhe = np.clip((dhs, dhe), 0, dh).astype(np.int)
return self.data[dhs:dhe:rateh, dws:dwe:ratew, :], (dws, dwe, dhs, dhe)
def refresh(self, *a):
fig = self.fig
ax = self.ax
vmin = self.vmin_ctrl.val
vmax = self.vmax_ctrl.val
w, h = get_ax_size(fig, ax)
bounds = ax.viewLim.bounds
xmin, ymin, xlen, ylen = bounds
xmax = xmin + xlen
ymax = ymin + ylen
data, extent = self.get_data(w, h, xmin, xmax, ymin, ymax)
data = data.astype(np.float32)
data = np.clip(data, vmin, vmax)
data = 255 * (data - vmin) / (vmax - vmin)
data = data.astype(np.uint8)
# fix aspect ratio
wl, wh, hl, hh = extent
aspect = (hh - hl) / float(wh - wl)
if self.ax_img is None:
self.ax_img = ax.imshow(data, aspect=aspect)
self.ax_img.set_extent((xmin, xmax, ymin, ymax))
self.ax.autoscale_view()
else:
self.ax_img.set_data(data)
self.ax_img.set_extent(np.clip((xmin, xmax, ymin, ymax), 0, 1))
xticks = np.linspace(xmin, xmax, 5)
yticks = np.linspace(ymin, ymax, 5)
xlabels = np.round(np.linspace(wl, wh, 5)).astype(np.int)
ylabels = np.round(np.linspace(hl, hh, 5)).astype(np.int)
self.ax.set_xticks(xticks)
self.ax.set_xticklabels(xlabels)
self.ax.set_yticks(yticks)
self.ax.set_yticklabels(ylabels)
fig.canvas.draw_idle()
def main():
parser = argparse.ArgumentParser(
"Select zone of interedt in an image"
"Select zone of interest in an image"
)
parser.add_argument('-ow', '--overwrite', action='store_true', help='Overwrite output directory if it exists')
required = parser.add_argument_group('Required arguments')
required.add_argument("-i","--input", required=True, help="Input file name of main image including extension.")
required.add_argument("-o","--output_folder", required=True, help="Name of output folder.")
......@@ -62,36 +176,55 @@ def main():
# Deal with existing output
if op.exists(outfolder):
print("Folder '{}' exists. Are you sure you want to delete it? [Y,N]".format(outfolder))
response = input()
if response.upper() == "Y":
shutil.rmtree(outfolder)
else:
overwrite = args.overwrite
if not overwrite:
print("Folder '{}' exists. Are you sure you want to delete it? [Y,N]".format(outfolder))
response = input()
overwrite = response.upper() == "Y"
if not overwrite:
print("Exiting without doing anything....")
sys.exit(1)
else:
shutil.rmtree(outfolder)
os.mkdir(outfolder)
# Read image
im = Image.open(image_name)
print("Reading input Image '{}' ...".format(image_name))
t0 = time.clock()
#im = Image.open(image_name)
im = skio.imread(image_name)
print(" ... this took {} seconds".format(time.clock()-t0))
image_base = op.basename(image_name)
# # Compare performances of readers
# t0 = time.clock()
# im = tif.imread(image_name)
# print(" ... tifffile took {} seconds".format(time.clock()-t0))
# t0 = time.clock()
# im = skio.imread(image_name)
# print(" ... skimage took {} seconds".format(time.clock()-t0))
# exit
# Resample image before showing it
res = 8
imr = np.asarray(im)[::res, ::res, :]
ax = plt.figure().add_subplot(111)
ax.imshow(imr)
plt.title('CLick and drag to draw zones')
print("Displaying ({} x {} pixels)...".format(*im.shape[:2]))
fig = plt.figure()
ax = fig.add_subplot(111)
fig.subplots_adjust(bottom=0.2)
plt.title('Click and drag to draw zones\n Close the window when done.')
zs = ZoneSelector(ax,op.join(outfolder,image_base),im,res)
biv = BigImageViewer(fig, ax, im)
zs = ZoneSelector(ax,op.join(outfolder,image_base),im)
plt.show()
if __name__ == '__main__':
main()
#!/usr/bin/env python3
from PIL import Image
#from PIL import Image
import tifffile as tif
import numpy as np
import matplotlib.pyplot as plt
import argparse
......@@ -47,7 +48,8 @@ def main():
coordinates = fcoord.readline()
x0, y0, x1, y1 = [float(number) for number in coordinates.split()]
im_z = Image.open(zone_image_name)
#im_z = Image.open(zone_image_name)
im_z = tif.imread(zone_image_name)
im_z_np = np.array(im_z)
(w,h,d) = im_z_np.shape
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment