def test_plot_plugin(): viewer = ImageViewer(data.moon()) plugin = PlotPlugin(image_filter=lambda x: x) viewer += plugin assert_equal(viewer.image, data.moon()) plugin._update_original_image(data.coins()) assert_equal(viewer.image, data.coins()) viewer.close()
def test_canny(): image = data.camera() viewer = ImageViewer(image) c = CannyPlugin() viewer += c canny_edges = viewer.show(False) viewer.close() edges = canny_edges[0][0] assert edges.sum() == 2852
def show_disparity_map(disparity_map): #Scale to zero: image = np.subtract(disparity_map, np.min(disparity_map)) if np.max(image) != 0: #Normalize and invert: image = np.multiply(image, 255.0/float(np.max(image))) #Show the stuff: viewer = ImageViewer(image.astype(np.uint8)) viewer.show()
def test_measure(): image = data.camera() viewer = ImageViewer(image) m = Measure() viewer += m m.line_changed([(0, 0), (10, 10)]) assert_equal(str(m._length.text), '14.1') assert_equal(str(m._angle.text[:5]), '135.0')
def test_color_histogram(): image = util.img_as_float(data.colorwheel()) viewer = ImageViewer(image) ch = ColorHistogram(dock='right') viewer += ch assert_almost_equal(viewer.image.std(), 0.352, 3), ch.ab_selected((0, 100, 0, 100)), assert_almost_equal(viewer.image.std(), 0.325, 3)
def test_viewer_with_overlay(): img = data.coins() ov = OverlayPlugin(image_filter=sobel) viewer = ImageViewer(img) viewer += ov import tempfile _, filename = tempfile.mkstemp(suffix='.png') ov.color = 3 assert_equal(ov.color, 'yellow') viewer.save_to_file(filename) ov.display_filtered_image(img) assert_equal(ov.overlay, img) ov.overlay = None assert_equal(ov.overlay, None) ov.overlay = img assert_equal(ov.overlay, img) assert_equal(ov.filtered_image, img)
def show_best_match(image_id, codebook, metric): bows = [x[1] for x in codebook] if metric == 'euclidean': m = euclidean_distance elif metric == 'kullback-leibler': m = symmetric_kullback_leibler elif metric == 'bhattacharyya': m = bhattacharyya_distance elif metric == 'common words': m = common_words else: return "Error" best_match_path = codebook[find_best_match(image_id, bows, m)][0] img = imread(best_match_path) view = ImageViewer(img) view.show()
def main(): imagefile = io.imread("colors.jpg") recolored_image = copy.deepcopy(imagefile) grayscale_matrix = np.array([0.2125, 0.7154, 0.0721]) # loop through every pixel for pixel_row_index in range(len(imagefile)): for pixel_index in range(len(imagefile[pixel_row_index])): if (imagefile[pixel_row_index][pixel_index][0] > 165 and imagefile[pixel_row_index][pixel_index][1] < 150 and imagefile[pixel_row_index][pixel_index][2] < 150) and ( imagefile[pixel_row_index][pixel_index][1] < imagefile[pixel_row_index][pixel_index][2] + 15): recolored_image[pixel_row_index][pixel_index] = imagefile[ pixel_row_index][pixel_index] else: recolored_image[pixel_row_index][pixel_index] = imagefile[ pixel_row_index][pixel_index].dot(grayscale_matrix) # transform rgb to hsv for hue color.rgb2hsv(imagefile) hue_original = get_hues(imagefile) color.rgb2hsv(recolored_image) hue_recolored = get_hues(recolored_image) #create plots fig, axs = plt.subplots(2) num_bins = 36 n, bins, patches = axs[0].hist(hue_original, num_bins, facecolor='blue', alpha=0.5) n, bins, patches = axs[1].hist(hue_recolored, num_bins, facecolor='red', alpha=0.5) plt.show() #grayscale = color.rgb2gray(imagefile) viewer = ImageViewer(recolored_image) viewer.show()
def preserve_color_cielch(content, stylized, image_name): # extract info and convert to CIE-LCh for each image rgbContent = io.imread(content) labContent = color.lab2lch( color.xyz2lab(color.rgb2xyz(numpy.asarray(rgbContent)))) labContentArray = numpy.array(labContent) rgbStyle = io.imread(stylized) labStyle = color.lab2lch( color.xyz2lab(color.rgb2xyz(numpy.asarray(rgbStyle)))) labStyleArray = numpy.array(labStyle) # color transfer for i in range(len(labContentArray)): for j in range(len(labContentArray[0])): labContentArray[i][j][0] = labStyleArray[i][j][0] labContentArray = color.xyz2rgb( color.lab2xyz(color.lch2lab(labContentArray))) viewer = ImageViewer(labContentArray) viewer.show()
def remove_object_loop(img): print("Remove object") viewer = ImageViewer(img) def on_enter(extens): coord = np.int64(extens) [x0, y0] = [coord[2], coord[0]] [x1, y1] = [coord[3], coord[1]] print([x0, y0], [x1, y1]) (x, y) = (x0, y0) (len_x, len_y) = (x1 - x, y1 - y) viewer.image = remove_object(viewer.image, x0, y0, len_x, len_y) rect_tool = RectangleTool(viewer, on_enter=on_enter) viewer.show() return viewer.image
def test_line_profile_dynamic(): """Test a line profile updating after an image transform""" image = data.coins()[:-50, :] # shave some off to make the line lower image = skimage.img_as_float(image) viewer = ImageViewer(image) lp = LineProfile(limits='dtype') viewer += lp line = lp.get_profiles()[-1][0] assert line.size == 129 assert_almost_equal(np.std(viewer.image), 0.208, 3) assert_almost_equal(np.std(line), 0.229, 3) assert_almost_equal(np.max(line) - np.min(line), 0.725, 1) viewer.image = skimage.img_as_float(median(image, selem=disk(radius=3))) line = lp.get_profiles()[-1][0] assert_almost_equal(np.std(viewer.image), 0.198, 3) assert_almost_equal(np.std(line), 0.220, 3) assert_almost_equal(np.max(line) - np.min(line), 0.639, 1)
def main(): filename_queue = tf.train.string_input_producer([tfrecords_filename]) image = read_and_decode(filename_queue) init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(3): img = sess.run([image]) img = img[0] print(img[0]) viewer = ImageViewer(img) viewer.show() coord.request_stop() coord.join(threads)
def go(img): def preprocess(img): U = {} V = {} s = {} for i in (0, 1, 2): res = svd(img[..., i], full_matrices=False) U[i] = np.mat(res[0]) V[i] = np.mat(res[2]) s[i] = res[1] return U, V, s U, V, s = preprocess(img) def display(_, R, G, B): rgb = (R, G, B) res = np.zeros_like(img) for i in (0, 1, 2): _s = s[i].copy() _s[rgb[i]:] = 0 S = np.mat(np.diag(_s)) res[..., i] = U[i] * S * V[i] return res def display_all(_, RGB): return display(_, RGB, RGB, RGB) viewer = ImageViewer(img) plugin = Plugin(image_filter=display) plugin.name = "" plugin += Slider('R', 0, len(s[0]), len(s[0]), 'int') plugin += Slider('G', 0, len(s[0]), len(s[1]), 'int') plugin += Slider('B', 0, len(s[0]), len(s[2]), 'int') viewer += plugin plugin = Plugin(image_filter=display_all) plugin.name = "" plugin += Slider('RGB', 0, len(s[0]), len(s[0]), 'int') viewer += plugin viewer.show()
def get_crop(image): ''' Show the original image to allow the user to crop any extraneous information out of the frame. :param image: 2D numpy array grayscale image :return: list of [left, right, top, bottom] values for the edges of the bounding box ''' plt.ioff() print('Waiting for input, please crop the image as desired and hit enter') viewer = ImageViewer(image) rect_tool = RectangleTool(viewer, on_enter=viewer.closeEvent) viewer.show() bounds = np.array(rect_tool.extents) if (bounds[0] < 0 or bounds[1] > image.shape[1] or bounds[2] < 0 or bounds[3] > image.shape[0]): print(f'Bounds = {bounds} and shape = {image.shape}') raise ValueError('Bounds outside image, make sure to select within') plt.ion() return np.array(np.round(bounds), dtype=int)
def test_label_painter(): image = data.camera() moon = data.moon() viewer = ImageViewer(image) lp = LabelPainter() viewer += lp assert_equal(lp.radius, 5) lp.label = 1 assert_equal(str(lp.label), '1') lp.label = 2 assert_equal(str(lp.paint_tool.label), '2') assert_equal(lp.paint_tool.radius, 5) lp._on_new_image(moon) assert_equal(lp.paint_tool.shape, moon.shape)
def test_base_tool(): img = data.moon() viewer = ImageViewer(img) tool = CanvasToolBase(viewer) tool.set_visible(False) tool.set_visible(True) do_event(viewer, 'key_press', key='enter') tool.redraw() tool.remove() tool = CanvasToolBase(viewer, useblit=False) tool.redraw()
def test_base_tool(): img = data.moon() viewer = ImageViewer(img) tool = CanvasToolBase(viewer.ax) tool.set_visible(False) tool.set_visible(True) enter = create_mouse_event(viewer.ax, key='enter') tool._on_key_press(enter) tool.redraw() tool.remove() tool = CanvasToolBase(viewer.ax, useblit=False) tool.redraw()
def viewer(): image = skimage.data.coins() viewer = ImageViewer(image) viewer.show() viewer += LineProfile(viewer) overlay, data = viewer.show()[0] #-------------------- denoise_plugin = Plugin( image_filter=skimage.restoration.denoise_tv_bregman) denoise_plugin += Slider('weight', 0.01, 0.5, update_on='release') denoise_plugin += SaveButtons() viewer = ImageViewer(image) viewer += denoise_plugin denoised = viewer.show()[0][0]
def test_thick_line_tool(): img = data.camera() viewer = ImageViewer(img) tool = ThickLineTool(viewer, maxdist=10) tool.end_points = get_end_points(img) do_event(viewer, 'scroll', button='up') assert_equal(tool.linewidth, 2) do_event(viewer, 'scroll', button='down') assert_equal(tool.linewidth, 1) do_event(viewer, 'key_press', key='+') assert_equal(tool.linewidth, 2) do_event(viewer, 'key_press', key='-') assert_equal(tool.linewidth, 1)
def test_thick_line_tool(): img = data.camera() viewer = ImageViewer(img) tool = ThickLineTool(viewer, maxdist=10, line_props=dict(color='red'), handle_props=dict(markersize=5)) tool.end_points = get_end_points(img) do_event(viewer, 'scroll', button='up') assert_equal(tool.linewidth, 2) do_event(viewer, 'scroll', button='down') assert_equal(tool.linewidth, 1) do_event(viewer, 'key_press', key='+') assert_equal(tool.linewidth, 2) do_event(viewer, 'key_press', key='-') assert_equal(tool.linewidth, 1)
def show_image_sample(image_directory, grid_shape, extensions=['jpg'], show=True, output_filename=None, thumbnail_size=100, assert_enough_images=True): """Creates image of a grid of images sampled from `image_directory`.""" if isinstance(thumbnail_size, int): size = (thumbnail_size, thumbnail_size) else: size = thumbnail_size def is_image(filename): return any(filename.lower().endswith(x.lower()) for x in extensions) image_files = [ os.path.join(image_directory, fn) for fn in os.listdir(image_directory) if is_image(fn) ] assert len(grid_shape) == 2 if assert_enough_images: assert grid_shape[0] * grid_shape[1] <= len(image_files) sample = np.random.choice(image_files, grid_shape) grid = [] for i in range(grid_shape[0]): row = [] for j in range(grid_shape[1]): row.append(resize(imread(sample[i, j]), size)) grid.append(np.concatenate(row, axis=1)) grid = (255 * np.concatenate(grid)).astype('uint8') if show: ImageViewer(grid).show() if output_filename is not None: imwrite(output_filename, grid)
def test_line_tool(): img = data.camera() viewer = ImageViewer(img) tool = LineTool(viewer, maxdist=10) tool.end_points = get_end_points(img) assert_equal(tool.end_points, np.array([[170, 256], [341, 256]])) # grab a handle and move it do_event(viewer, 'mouse_press', xdata=170, ydata=256) do_event(viewer, 'move', xdata=180, ydata=260) do_event(viewer, 'mouse_release') assert_equal(tool.geometry, np.array([[180, 260], [341, 256]])) # create a new line do_event(viewer, 'mouse_press', xdata=10, ydata=10) do_event(viewer, 'move', xdata=100, ydata=100) do_event(viewer, 'mouse_release') assert_equal(tool.geometry, np.array([[100, 100], [10, 10]]))
def test_thick_line_tool(): img = data.camera() viewer = ImageViewer(img) tool = ThickLineTool(viewer.ax, maxdist=10) tool.end_points = get_end_points(img) scroll_up = create_mouse_event(viewer.ax, button='up') tool.on_scroll(scroll_up) assert_equal(tool.linewidth, 2) scroll_down = create_mouse_event(viewer.ax, button='down') tool.on_scroll(scroll_down) assert_equal(tool.linewidth, 1) key_up = create_mouse_event(viewer.ax, key='+') tool.on_key_press(key_up) assert_equal(tool.linewidth, 2) key_down = create_mouse_event(viewer.ax, key='-') tool.on_key_press(key_down) assert_equal(tool.linewidth, 1)
def test_line_tool(): img = data.camera() viewer = ImageViewer(img) tool = LineTool(viewer.ax, maxdist=10) tool.end_points = get_end_points(img) assert_equal(tool.end_points, np.array([[170, 256], [341, 256]])) # grab a handle and move it grab = create_mouse_event(viewer.ax, xdata=170, ydata=256) tool.on_mouse_press(grab) move = create_mouse_event(viewer.ax, xdata=180, ydata=260) tool.on_move(move) tool.on_mouse_release(move) assert_equal(tool.geometry, np.array([[180, 260], [341, 256]])) # create a new line new = create_mouse_event(viewer.ax, xdata=10, ydata=10) tool.on_mouse_press(new) move = create_mouse_event(viewer.ax, xdata=100, ydata=100) tool.on_move(move) tool.on_mouse_release(move) assert_equal(tool.geometry, np.array([[100, 100], [10, 10]]))
def test_plugin(): img = skimage.img_as_float(data.moon()) viewer = ImageViewer(img) def median_filter(img, radius=3): return median(img, selem=disk(radius=radius)) plugin = Plugin(image_filter=median_filter) viewer += plugin plugin += Slider('radius', 1, 5) assert_almost_equal(np.std(viewer.image), 12.556, 3) plugin.filter_image() assert_almost_equal(np.std(viewer.image), 12.931, 3) plugin.show() plugin.close() plugin.clean_up() img, _ = plugin.output() assert_equal(img, viewer.image)
def test_rect_tool(): img = data.camera() viewer = ImageViewer(img) tool = RectangleTool(viewer, maxdist=10) tool.extents = (100, 150, 100, 150) assert_equal(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150))) assert_equal(tool.extents, (100, 150, 100, 150)) assert_equal(tool.edge_centers, ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))) assert_equal(tool.geometry, (100, 150, 100, 150)) # grab a corner and move it do_event(viewer, 'mouse_press', xdata=100, ydata=100) do_event(viewer, 'move', xdata=120, ydata=120) do_event(viewer, 'mouse_release') assert_equal(tool.geometry, [120, 150, 120, 150]) # create a new line do_event(viewer, 'mouse_press', xdata=10, ydata=10) do_event(viewer, 'move', xdata=100, ydata=100) do_event(viewer, 'mouse_release') assert_equal(tool.geometry, [10, 100, 10, 100])
def show_matching(img, img2, matching): print "matching..." ip_match = build_match_dic(img, img2, matching) print "Constructing intermediate image..." padding = 5 #padding around the edges bar = np.ndarray((img.shape[0], 5)) bar.fill(1.0) viewer = ImageViewer(img) viewer.show() img3 = np.column_stack((img, bar, img2)) viewer = ImageViewer(img3) viewer.show() img3 = img_as_ubyte(img3) viewer = ImageViewer(img3) viewer.show() img3 = np.pad(img3, pad_width=padding, mode='constant', constant_values=(0)) viewer = ImageViewer(img3) viewer.show() print "Drawing lines..." colimg = color.gray2rgb(img3) for k,v in random.sample(ip_match.items(), int(float(len(ip_match.keys()))*0.005)): #Choose a random colour: col = [random.randint(0,255),random.randint(0,255),random.randint(0,255)] #Calculate coordinates after padding: x1 = k[0]+padding y1 = k[1]+padding x2 = v[0]+padding y2 = v[1] + img.shape[1]+bar.shape[1]+padding #Draw the points in both images: rr, cc = circle_perimeter(x1, y1, 3) colimg[rr, cc] = col rr, cc = circle_perimeter(x2, y2, 3) colimg[rr, cc] = col #Draw a line between the points: rr, cc = line(x1,y1,x2,y2) colimg[rr, cc] = col #Show the result: viewer = ImageViewer(colimg) viewer.show()
def check(train_set_x, train_set_y, val_set_x, val_set_y): print(train_set_y[0]) viewer = ImageViewer(train_set_x[0]) viewer.show() print(train_set_y[10]) viewer = ImageViewer(train_set_x[10]) viewer.show() print(train_set_y[32]) viewer = ImageViewer(train_set_x[32]) viewer.show() print(train_set_y[56]) viewer = ImageViewer(train_set_x[56]) viewer.show() print(train_set_y[76]) viewer = ImageViewer(train_set_x[76]) viewer.show() print(train_set_y[119]) viewer = ImageViewer(train_set_x[119]) viewer.show() print(val_set_y[5]) viewer = ImageViewer(val_set_x[5]) viewer.show() print(val_set_y[13]) viewer = ImageViewer(val_set_x[13]) viewer.show() print(val_set_y[32]) viewer = ImageViewer(val_set_x[32]) viewer.show() print(val_set_y[51]) viewer = ImageViewer(val_set_x[51]) viewer.show() print(val_set_y[75]) viewer = ImageViewer(val_set_x[75]) viewer.show() print(val_set_y[145]) viewer = ImageViewer(val_set_x[145]) viewer.show()
R, G, B = 0, 1, 2 # select regions where red is less than 100 mask = source[R].point(lambda i: i < 100 and 255) # process the green band out = source[G].point(lambda i: i * 0.7) # paste the processed band back, but only where red was < 100 source[G].paste(out, None, mask) # build a new multiband image im = Image.merge(img.mode, source) # im.show() # Python Imaging Library 使用笛卡尔坐标系, 使用 (0,0) 表示左上角. 值得注意的是, 坐标点表示的是一个像素的左上角, 而表示像素的中央则是 (0.5,0.5) # skimage 部分 camera = data.camera() print(camera, camera.shape, type(camera)) # 打开本地文件 dancing = io.imread(fp) print(dancing, dancing.shape, type(dancing)) # Images manipulated by scikit-image are simply NumPy arrays print(dancing.min(), dancing.max(), dancing.mean()) # plt.imshow(dancing) # plt.show() viewer = ImageViewer(dancing) viewer.show()
if self.active_handle is None: # New rectangle x1 = self.eventpress.xdata y1 = self.eventpress.ydata x2, y2 = event.xdata, event.ydata else: x1, x2, y1, y2 = self._extents_on_press if self.active_handle in ['E', 'W'] + self._corner_order: x2 = event.xdata if self.active_handle in ['N', 'S'] + self._corner_order: y2 = event.ydata self.extents = (x1, x2, y1, y2) self.callback_on_move(self.geometry) @property def geometry(self): return self.extents if __name__ == '__main__': # pragma: no cover from skimage.viewer import ImageViewer from skimage import data viewer = ImageViewer(data.camera()) rect_tool = RectangleTool(viewer) viewer.show() print("Final selection:") rect_tool.callback_on_enter(rect_tool.extents)
def test_viewer(): astro = data.astronaut() coins = data.coins() view = ImageViewer(astro) import tempfile _, filename = tempfile.mkstemp(suffix='.png') view.show(False) view.close() view.save_to_file(filename) view.open_file(filename) assert_equal(view.image, astro) view.image = coins assert_equal(view.image, coins), view.save_to_file(filename), view.open_file(filename), view.reset_image(), assert_equal(view.image, coins)
import openslide import numpy as np import skimage from skimage.viewer import ImageViewer import PIL import matplotlib.pyplot as plt slide = openslide.open_slide( "../CAMELYON/data/patient_013/patient_013_node_0.tif") slide level = 6 dims = slide.level_dimensions[level] slide.level_downsamples[level] pixelarray = np.array(slide.read_region((0, 0), level, dims)) pixelarray.shape viewer = ImageViewer(pixelarray) viewer.show()
from skimage import data from skimage.filters.rank import median from skimage.morphology import disk from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider, OKCancelButtons, SaveButtons from skimage.viewer.plugins.base import Plugin def median_filter(image, radius): return median(image, selem=disk(radius)) image = data.coins() viewer = ImageViewer(image) plugin = Plugin(image_filter=median_filter) plugin += Slider('radius', 2, 10, value_type='int') plugin += SaveButtons() plugin += OKCancelButtons() viewer += plugin viewer.show()
from skimage import data from skimage.viewer import ImageViewer from skimage.viewer.plugins.lineprofile import LineProfile image = data.camera() viewer = ImageViewer(image) viewer += LineProfile() line, profile = viewer.show()[0]
from skimage import data from skimage.filters import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5) plugin += Slider('low threshold', 0, 255) plugin += Slider('high threshold', 0, 255) # ... and we can also add buttons to save the overlay: plugin += SaveButtons(name='Save overlay to:') # Finally, attach the plugin to an image viewer. viewer = ImageViewer(image) viewer += plugin canny_edges = viewer.show()[0][0]
from skimage.viewer.plugins.canny import CannyPlugin def line_image(shape, lines): image = np.zeros(shape, dtype=bool) for end_points in lines: end_points = np.asarray(end_points)[:, ::-1] image[draw.line(*np.ravel(end_points))] = 1 return image def hough_lines(image, *args, **kwargs): lines = probabilistic_hough_line(image, threshold=0.5, *args, **kwargs) image = line_image(image.shape, lines) return image image = data.camera() canny_viewer = ImageViewer(image) canny_plugin = CannyPlugin() canny_viewer += canny_plugin hough_plugin = OverlayPlugin(image_filter=hough_lines) hough_plugin += Slider('line length', 0, 100, value=100, update_on='move') hough_plugin += Slider('line gap', 0, 20, value=0, update_on='move') hough_viewer = ImageViewer(canny_plugin) hough_viewer += hough_plugin canny_viewer.show()
def show(self): viewer = ImageViewer(self.image) viewer.show()
def setup_line_profile(image, limits='image'): viewer = ImageViewer(skimage.img_as_float(image)) plugin = LineProfile(limits=limits) viewer += plugin return plugin
from skimage import data from skimage.viewer import ImageViewer from skimage.viewer.plugins.measure import Measure image = data.camera() viewer = ImageViewer(image) viewer += Measure() viewer.show()
def viewImage(image): viewer = ImageViewer(image) viewer.show()
from skimage import data from skimage.viewer import ImageViewer from skimage.viewer.plugins.lineprofile import LineProfile image = data.chelsea() viewer = ImageViewer(image) viewer += LineProfile() line, rgb_profiles = viewer.show()[0]
def testinterp(noiselevel, pointfrac): # Definitions dimx = 100 dimy = 100 dens = 0.1 dx2 = dimx/2 dy2 = dimy/2 startval = 3.0 l = 0.01 maxitt = 10 # define ground truth GT = np.zeros((dimx, dimy)) GT[0:dx2,0:dy2] = - 10.0 GT[0:dx2,dy2+1:] = 0.0 GT[dx2+1:,0:dy2] = 5.0 GT[dx2+1:,dy2+1:] = 15.0 # generate data Data = GT + noiselevel*np.random.randn(dimx,dimy) points = (np.random.rand(dimx,dimy) < pointfrac) values = np.multiply((1*points), Data) start = startval*np.ones((dimx,dimy)) print "Interpolating..." Ipim = interp(start, points, values, maxitt, l) print "Done!" # compare and display result err1 = (Data - Ipim) err = np.absolute(Data - Ipim) errsq = err1.dot(err1) rms= math.sqrt(errsq.sum())/float(dimx*dimy) print 'average reconstruction error:', rms shGT = GT - GT.min() shGT = shGT/float(shGT.max()) shIp = Ipim - Ipim.min() shIp = shIp/float(shIp.max()) sher = err - err.min() sher = sher/float(sher.max()) #h = figure(1); #subplot(2,2,1); print "ground truth" view = ImageViewer(shGT) view.show() print 'Reconstruction' view = ImageViewer(shIp) view.show() print 'Sparse point position' view = ImageViewer(points) view.show() print 'Reconstruction error' view = ImageViewer(sher) view.show()
class SignalRetriever(): fun = lambda x, y, z: np.logical_or(x, np.logical_or(y, z)) view_func = lambda x: ImageViewer(x).show() @staticmethod def get_baseline(image_src): pass @staticmethod def transform_to_binary_image(image_src, corrector=35): #La funcion transforma la imagen a blanco y negro haciendo su mejor esfuerzo #por preservar las líneas de la señal del ECG. # Esta funcion realiza resalta los negros dado un determinado factor para # visualizar la senial. fun_corrector = lambda x: lambda y: int( x == y) * y * corrector // 100 + int(x != y) * y fun = SignalRetriever.fun #Lectura de la imagen y posterior ajuste de Gamma (Para que eliminar difuminadso) image = sexp.adjust_gamma(image_src, 1.25) #Datos importantes para la imagen try: image_aux = np.reshape( image, (image.shape[0] * image.shape[1], image.shape[2])) except IndexError: pass #El color que mas aparece color_dominance = np.sum(image_aux, 0) color_max = np.max(color_dominance) index_max = np.where(color_dominance == color_max) index_max = index_max[0][0] #Threshold para cada canal de la imagen rgb_t = list( map(lambda x: sfil.threshold_isodata(x), [image_aux[:, i] for i in range(3)])) fun_corrector = fun_corrector(rgb_t[index_max]) #Aplicando threshold a cada canal y unificando image_aux = fun(image_aux[:, 0] > fun_corrector(rgb_t[0]), image_aux[:, 1] > fun_corrector(rgb_t[1]), image_aux[:, 2] > fun_corrector(rgb_t[2])) #Redimensionando la imagen. bn_im = np.reshape(image_aux, (image.shape[0], image.shape[1])) return bn_im @staticmethod def retrieve_signal(points, image_src): # Esta funcion toma los pixeles marcados y realiza una interpolacion con los pixeles # obtenido del procesamiento de la imagen y_standarized = (image_src.shape[0] - points[0]).astype(float) inter_func = interp1d(points[1], y_standarized) return inter_func @staticmethod def plot_digital_ecg(inter_func, points): #Funcion de prueba para ver como se ve la señal luego de una interpolación. x = np.linspace(np.min(points[1]), np.max(points[1]), 750) plt.plot(x, inter_func(x)) plt.axes().set_aspect('equal', 'box') plt.show() @staticmethod def sample_signal(inter_func, points): # Guardando archivo de la señal. x = np.linspace(np.min(points[1]), np.max(points[1]), 750) x = inter_func(x) sdx = np.std(x) x -= np.mean(x) x /= sdx x = np.reshape(x, (x.shape[0], 1)) # record = wfdb.Record(recordname='Test1',fs=300,nsig=1,siglen=750,p_signals=x, # filename=['test.dat'],baseline=[-1],units=['mV'],signame=['ECG']) # wfdb.plotrec(record,title='Test') return x def __init__(self, *args, **kwargs): self.images_src = args self.dir = kwargs.get('dir') exclude = kwargs.get('exclude') # Hay archivos para excluir ? if exclude: #exclude_files = open(exclude,'r') exclude_files = ['img_0.jpg', 'img_0_II_long.jpg'] # json parse self.images_src = list( map( lambda x: self.dir + '/' + x, filter( lambda x: x not in exclude_files or x[-6:] == 'bn.jpg', self.images_src))) def get_multisignal_from_images(self): images = sio.imread_collection(self.images_src) i = 0 array_signal = [] for image in images: points, bn_image = SignalRetriever.transform_to_binary_image( image, corrector=15) #imsave(self.dir+'/'+'img_{0}_bn.jpg'.format(i),bn_image) inter_func = SignalRetriever.retrieve_signal(points, image) x = SignalRetriever.sample_signal(inter_func, points) # record = wfdb.Record(recordname='Test'+str(i),fs=300,nsig=1,siglen=750,p_signals=x, # filename=['test.dat'],baseline=[50],units=['mV'],signame=['ECG'],adcgain=[200],fmt=['16'],checksum=[0], # adcres=[16],adczero=[0],initvalue=[0],blocksize=[0], d_signals=None) #array_signal = np.concatenate((array_signal,SignalRetriever.sample_signal(inter_func,points))) array_signal.append(x) i += 1 return array_signal
import skimage as sk from skimage.viewer import ImageViewer #import TomographyTools as tt #import TomographyTools.data_management as dm #import TomographyTools.reconstruciton as rn import TomographyTools.image_processing as ip inputDir = "/home/[email protected]/data-scratch/20171006_ChaiLor_PaintData/rec20171005_162920_TiO2_sample1/" inputDirs = ['/home/[email protected]/data-scratch/20171006_ChaiLor_PaintData/rec20171005_155036_TiO2_control_scan2', "/home/[email protected]/data-scratch/20171006_ChaiLor_PaintData/rec20171005_162920_TiO2_sample1/", '/home/[email protected]/data-scratch/20171006_ChaiLor_PaintData/rec20171005_165313_TiO2_sample2', '/home/[email protected]/data-scratch/20171006_ChaiLor_PaintData/rec20171005_172237_TiO2_sample3'] if True: ip.convert_DirectoryTo8Bit(inputpath=inputDirs[0],data_min=-5.0,data_max=7.0) ip.convert_DirectoryTo8Bit(inputpath=inputDirs[1],data_min=-5.0,data_max=7.0) ip.convert_DirectoryTo8Bit(inputpath=inputDirs[2],data_min=-5.0,data_max=7.0) ip.convert_DirectoryTo8Bit(inputpath=inputDirs[3],data_min=-5.0,data_max=7.0) if False: imageStack = ip.loadDataStack(inputDir) imageStack8Bit = ip.convert8bit(imageStack,-5.0,7.0) ip.saveTiffStack(imageStack,filename="testStack_8Bit") image = imageStack8Bit[:,:,50] viewer = ImageViewer(image); viewer.show()