def main(): args = parse_args() syris.init(device_index=0) m = 20 if args.input == 'grid': image = make_grid(args.n, m * q.m).thickness.get() elif args.input == 'lena': from scipy.misc import lena image = lena().astype(cfg.PRECISION.np_float) if args.n != image.shape[0]: image = gutil.get_host(ip.rescale(image, (args.n, args.n))) n = image.shape[0] crop_n = n - 2 * m - 2 y, x = np.mgrid[-n / 2:n / 2, -n / 2:n / 2] # Compute a such that the disk diameter is exactly the period when distance from the middle is n # / 2 a = m / (2 * (crop_n / 2.) ** 2) radii = (a * np.sqrt(x ** 2 + y ** 2) ** 2 + 1e-3).astype(cfg.PRECISION.np_float) x_param = radii y_param = radii result = ip.varconvolve_disk(image, (y_param, x_param)).get() result = ip.crop(result, (m - 1, m - 1, crop_n, crop_n)).get() radii = ip.crop(radii, (m - 1, m - 1, crop_n, crop_n)).get() image = ip.crop(image, (m - 1, m - 1, crop_n, crop_n)).get() if args.output: save_image(args.output, result) show(image, title='Original Image') show(2 * radii, title='Blurring Disk Diameters') show(result, title='Blurred Image') plt.show()
def get_weight_lena(sigma=50000.): """ Calculates the weight matrix of a small patch of lena's image Parameters ---------- sigma: int Returns ------- """ lena = misc.lena() lena = lena[:30:, :30] patches = [] for i in range(lena.shape[0] - 7): for j in range(lena.shape[1] - 7): patches.append(lena[i:i + 6, j:j + 6].flatten()) dist = np.exp(- euclidean_distances(patches, patches) ** 2 / sigma ** 2) thres = dist.copy() thres.sort(axis=1) thres = thres[:, ::-1][:, 6] dist[dist < thres] = 0 return dist
def test_cercle(): im = lena() roi = roi_quad(im.shape,250,250,400) im = np.multiply(roi,im) plt.imshow(im) plt.show()
def initTexture(self): """ init the texture - this has to happen after an OpenGL context has been created """ # make the OpenGL context associated with this canvas the current one #self.SetCurrent() data = np.uint8(np.flipud(lena())) w,h = data.shape # generate a texture id, make it current self.texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D,self.texture) # texture mode and parameters controlling wrapping and scaling gl.glTexEnvf( gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE ) gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT ) gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT ) gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR ) gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR ) # map the image data to the texture. note that if the input # type is GL_FLOAT, the values must be in the range [0..1] gl.glTexImage2D(gl.GL_TEXTURE_2D,0,gl.GL_RGB,w,h,0, gl.GL_LUMINANCE,gl.GL_UNSIGNED_BYTE,data)
def IST(): from scipy.misc import lena #from numpy.random import random seed(42) x = lena() xx = x + np.random.random(x.shape) * 255 / 10 xx, ys = ISTreal(xx, p=1.0) xx = idwt2_full(xx) a = np.random.random(x.shape) * 255 / 10 error = abs(xx - x) print mean(a) print mean(error) imshow(error) show() subplot(121) imshow(ys, cmap='gray') subplot(122) imshow(xx, cmap='gray') savefig('stackexchange.png', dpi=300) show()
def _plot_default(self): # Create a GridContainer to hold all of our plots: 2 rows, 4 columns: container = GridContainer(fill_padding=True, bgcolor="lightgray", use_backbuffer=True, shape=(2, 4)) arrangements = [('top left', 'h'), ('top right', 'h'), ('top left', 'v'), ('top right', 'v'), ('bottom left', 'h'), ('bottom right', 'h'), ('bottom left', 'v'), ('bottom right', 'v')] orientation_name = {'h': 'horizontal', 'v': 'vertical'} pd = ArrayPlotData(image=lena()) # Plot some bessel functions and add the plots to our container for origin, orientation in arrangements: plot = Plot(pd, default_origin=origin, orientation=orientation) plot.img_plot('image') # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) title = '{0}, {1}' plot.title = title.format(orientation_name[orientation], origin.replace(' ', '-')) # Add to the grid container container.add(plot) return container
def setUp(self): im = lena() self.lena_offset = np.array((256, 256)) s = hs.signals.Image(np.zeros((10, 100, 100))) self.scales = np.array((0.1, 0.3)) self.offsets = np.array((-2, -3)) izlp = [] for ax, offset, scale in zip( s.axes_manager.signal_axes, self.offsets, self.scales): ax.scale = scale ax.offset = offset izlp.append(ax.value2index(0)) self.izlp = izlp self.ishifts = np.array([(0, 0), (4, 2), (1, 3), (-2, 2), (5, -2), (2, 2), (5, 6), (-9, -9), (-9, -9), (-6, -9)]) self.new_offsets = self.offsets - self.ishifts.min(0) * self.scales zlp_pos = self.ishifts + self.izlp for i in xrange(10): slices = self.lena_offset - zlp_pos[i, ...] s.data[i, ...] = im[slices[0]:slices[0] + 100, slices[1]:slices[1] + 100] self.spectrum = s # How image should be after successfull alignment smin = self.ishifts.min(0) smax = self.ishifts.max(0) offsets = self.lena_offset + self.offsets / self.scales - smin size = np.array((100, 100)) - (smax - smin) self.aligned = im[offsets[0]:offsets[0] + size[0], offsets[1]:offsets[1] + size[1]]
def run(self, img=misc.lena(), increase=True): img = misc.imread('/Users/Daniel/Desktop/p0.jpg') img_blurred = self.__blur(img) img = self.__divide(img, img_blurred) if False: img = exposure.adjust_sigmoid(img) misc.imsave('/Users/Daniel/Desktop/p1.jpg', img)
def get_image(): # Build Image try: filename = sys.argv[1] image = ndimage.imread(filename, flatten=True).astype(np.float32) except IndexError: image = misc.lena().astype(np.float32) return image
def pytest_generate_tests(metafunc): """ Generates a set of test for the registration methods. """ image = misc.lena() image = nd.zoom(image, 0.50) if metafunc.function is test_shift: for displacement in np.arange(-10.,10.): p = np.array([displacement, displacement]) template = warp( image, p, model.Shift, sampler.Spline ) metafunc.addcall( id='dx={}, dy={}'.format( p[0], p[1] ), funcargs=dict( image=image, template=template, p=p ) ) if metafunc.function is test_affine: # test the displacement component for displacement in np.arange(-10.,10.): p = np.array([0., 0., 0., 0., displacement, displacement]) template = warp( image, p, model.Affine, sampler.Spline ) metafunc.addcall( id='dx={}, dy={}'.format( p[4], p[5] ), funcargs=dict( image=image, template=template, p=p ) )
def plot_lena_overlay(): plt.figure() logo = ScipyLogo((300, 300), 180) logo.plot_snake_curve() logo.plot_circle() img = lena() #mask = logo.get_mask(img.shape, 'upper left') #img[mask] = 255 plt.imshow(img)
def setUp( self ): import numpy as np self.np = np from scipy.misc import lena self.lena = lena() self.raw = np.zeros((1,512,512,1,1)) self.raw[0,:,:,0,0] = self.lena self.source = ArraySource( self.raw )
def main(): img = lena() frames, desc = imagesift.get_sift_keypoints(img) out = imagesift.draw_sift_frames(img, frames) cv2.imshow('sift image', out) cv2.waitKey(0)
def main(): print "Loading Lena image..." # img_size = 50, 50 # orig_img = misc.lena()[160:160+img_size[0], 160:160+img_size[1]] orig_img = misc.lena() print "Image dtype: %s" % orig_img.dtype print "Image size: %6d" % orig_img.size print "Image shape: %3dx%3d" % (orig_img.shape[0], orig_img.shape[1]) print "Max value %3d at pixel %6d" % (orig_img.max(), orig_img.argmax()) print "Min value %3d at pixel %6d" % (orig_img.min(), orig_img.argmin()) print "Variance: %1.5f" % orig_img.var() print "Standard deviation: %1.5f" % orig_img.std() misc.imsave("orig.png", orig_img) # Generate additive white Gaussian noise (AWGN) print "Generating noisy image..." if len(sys.argv) == 2: # Use sigma specified by the user user_sigma = float(sys.argv[1]) noise = get_noise(noise_size=orig_img.size, noise_sigma=user_sigma) else: # Use default sigma noise = get_noise(noise_size=orig_img.size) nois_img = get_noisy_img(orig_img, noise) misc.imsave("noisy.png", nois_img) # Normalize image, that is, translate values in image so its # distribution is comparable to a normal N(0, 1) (mean = 0.0, # standard deviation = 1.0). This way, parameters of the denoising # algorithm, like h and sigma, are independent of the values and # distribution of the image. print "Normalizing noisy image..." nois_img_mean = nois_img.mean() nois_img_std = nois_img.std() normal_nois_img = nois_img - nois_img_mean if nois_img_std > 0.01: # Divide by std. dev. if it is not zero normal_nois_img /= nois_img_std # Test saving and loading a noisy image. print "Saving as TMP format..." save_to_tmp("noisy.tmp", normal_nois_img) print "Load from TMP format..." loaded_img = load_from_tmp("noisy.tmp")[0] # Check if saved and loaded image are quite similar (some small error # could be expected) if numpy.allclose(normal_nois_img, loaded_img): print "Saved and loaded images are equal" else: print "Saved and loaded images are NOT equal"
def __init__(self): iris = datasets.load_iris() self._x_iris = iris.data self._y_iris = iris.target try: self._lena = sp.lena() except AttributeError: from scipy import misc self._lena = misc.lena()
def gen_lena(): """ Generate a (512, 512, 2) matrix where first layer is lena image. And the second layer is an array of 0s """ from scipy.misc import lena lena = np.atleast_3d(lena()).astype(np.float32) zeros = np.zeros_like(lena) feats = np.dstack([lena, zeros]) return feats
def task5(): img_mat = np.asarray(normalize_intensity(lena())) outputs = dict() for param in (0.1, 0.3, 0.8): outputs[param] = salt_and_pepper_noise(img_mat, param) file_name = 'noisy_{}.png'.format(str(param).replace('.', '_')) imsave(os.path.join(OUTPUT_DIR, file_name), outputs[param]) pl.imshow(outputs[0.1], cmap=cm.Greys_r) pl.show()
def test_downsample(): """ Tests register data down-sampling. """ image = register.RegisterData(misc.lena()) for factor in [1, 2, 4, 6, 8 ,10]: subSampled = image.downsample(factor) assert subSampled.data.shape[0] == image.data.shape[0] / factor assert subSampled.data.shape[1] == image.data.shape[1] / factor assert subSampled.coords.spacing == factor
def main(): print "Loading Lena image..." orig_img = misc.lena()[160:160+10, 160:160+10] print "Image dtype: %s" % orig_img.dtype print "Image size: %6d" % orig_img.size print "Image shape: %3dx%3d" % (orig_img.shape[0], orig_img.shape[1]) print "Max value %3d at pixel %6d" % (orig_img.max(), orig_img.argmax()) print "Min value %3d at pixel %6d" % (orig_img.min(), orig_img.argmin()) print "Variance: %1.5f" % orig_img.var() print "Standard deviation: %1.5f" % orig_img.std() misc.imsave("orig.png", orig_img) print "Generating noisy image..." print "Noise standard deviation: %1.5f" % noise_sigma # Generate additive white Gaussian noise (AWGN) with specifed sigma normal_noise = np.random.normal(scale=noise_sigma, size=orig_img.size) normal_noise = normal_noise.reshape(orig_img.shape) nois_img = orig_img + normal_noise misc.imsave("noisy.png", nois_img) # Normalize image, that is, translate values in image so its distribution # is comparable to a normal N(0, 1) (mean = 0.0, standard deviation = 1.0). # This way, parameters of the denoising algorithm, like h and sigma, are # independent of the values and distribution of the image. print "Normalizing noisy image..." nois_img_mean = nois_img.mean() nois_img_std = nois_img.std() normal_nois_img = np.empty(nois_img.shape, dtype=np.float32) for x in xrange(normal_nois_img.shape[0]): for y in xrange(normal_nois_img.shape[1]): normal_nois_val = nois_img[x, y] - nois_img_mean if nois_img_std != 0.000001: normal_nois_val /= nois_img_std normal_nois_img[x, y] = normal_nois_val print "Denoising image..." normal_rest_img = denoise2D(normal_nois_img, True) print "Denormalizing noisy image..." rest_img = np.empty(nois_img.shape, dtype=orig_img.dtype) for x in xrange(rest_img.shape[0]): for y in xrange(rest_img.shape[1]): rest_val = normal_rest_img[x, y] * nois_img_std rest_val += nois_img_mean rest_img[x, y] = rest_val print "Storing denoised image..." misc.imsave("denoised.png", rest_img)
def test_test_lena_npy_array(): arr_in = lena()[::32, ::32].astype(DTYPE) idx = [[4, 2], [4, 2]] gt = np.array([1280.99987793, 992.0], dtype=DTYPE) arr_out = lpool(arr_in, plugin=plugin, plugin_kwargs=plugin_kwargs) gv = arr_out[idx] assert_allclose_round(gv, gt, rtol=RTOL, atol=ATOL)
def setUp( self ): import numpy as np self.np = np from scipy.misc import lena self.lena = lena() self.raw = np.zeros((1,512,512,1,1), dtype=np.uint8) self.raw[0,:,:,0,0] = self.lena g = Graph() op = OpDataProvider(g, self.raw) self.source = LazyflowSource(op, "Data")
def test_CubicSpline_estimate(): """ Asserts that scaling a warp field is a reasonable thing to do. """ scale = 2.0 # Form a high resolution image. high = register.RegisterData(misc.lena().astype(np.double)) # Form a low resolution image. low = high.downsample(scale) # Make a deformed low resolution image. p = model.CubicSpline(low.coords).identity p += np.random.rand(p.shape[0]) * 100 - 50 warp = model.CubicSpline(low.coords).transform(p) dlow = sampler.Nearest(low.coords).f( low.data, low.coords.tensor - warp ).reshape(low.data.shape) # Scale the low resolution warp field to the same size as the high resolution # image. hwarp = np.array( [nd.zoom(warp[0],scale), nd.zoom(warp[1],scale)] ) * scale # Estimate the high resolution spline parameters that best fit the # enlarged warp field. invB = np.linalg.pinv(model.CubicSpline(high.coords).basis) pHat = np.hstack( (np.dot(invB, hwarp[1].flatten()), np.dot(invB, hwarp[0].flatten())) ) warpHat = model.CubicSpline(high.coords).warp(pHat) # Make a deformed high resolution image. dhigh = sampler.Nearest(high.coords).f(high.data, warpHat).reshape(high.data.shape) # down-sample the deformed high-resolution image and assert that the # pixel values are "close". dhigh_low = nd.zoom(dhigh, 1.0/scale) # Assert that the down-sampler highresolution image is "roughly" similar to # the low resolution image. assert (np.abs((dhigh_low[:] - dlow[:])).sum() / dlow.size < 10.0), \ "Normalized absolute error is greater than 10 pixels."
def test_strides_scipy_naive(): arr_in = lena() / 1.0 arr_in = arr_in[:12, :12] for stride in xrange(1, 12): try: gt = lpool(arr_in, stride=stride, plugin="scipy_naive") gv = lpool(arr_in, stride=stride, plugin=plugin, plugin_kwargs=plugin_kwargs) assert_array_equal(gv, gt) except NotImplementedError: raise SkipTest
def old_ex(): img = lena() # the underlying signal is a sinusoidally modulated image t = np.arange(100) time = np.sin(0.1 * t) real = time[:, np.newaxis, np.newaxis] * img[np.newaxis, ...] # we add some noise noisy = real + np.random.randn(*real.shape) * 255 # (observations, features) matrix M = noisy.reshape(noisy.shape[0], -1)
def main(): pub = rospy.Publisher('image', Image, queue_size=1) img = cv2.cvtColor(lena().astype(np.uint8), cv2.COLOR_GRAY2BGR) bridge = cv_bridge.CvBridge() msg = bridge.cv2_to_imgmsg(img, encoding='bgr8') msg.header.frame_id = 'camera' # publish in 30 hz rate = rospy.Rate(30) while not rospy.is_shutdown(): msg.header.stamp = rospy.get_rostime() pub.publish(msg) rate.sleep()
def test_2d(fac = .3): from scipy.misc import lena d = lena().astype(np.float32) d = d[:,:-10] sig = .2*np.amax(d) y = d+sig*np.random.uniform(0,1.,d.shape) out = nlm2(y.astype(np.float32),fac*sig,3,5) return out
def test_test_lena_pt3_array(): lena32 = lena()[::32, ::32].astype(DTYPE) / 255.0 arr_in = Array(lena32.shape, dtype=DTYPE) arr_in[:] = lena32 idx = [[4, 2], [4, 2]] gt = np.array([5.02353001, 3.89019608], dtype=DTYPE) arr_out = lpool(arr_in, plugin=plugin, plugin_kwargs=plugin_kwargs) gv = arr_out[idx] assert_allclose_round(gv, gt, rtol=RTOL, atol=ATOL)
def test_lena_npy_array(): arr_in = lena()[::32, ::32].astype(DTYPE) idx = [[4, 2], [4, 2]] gt = np.array([0.2178068, 0.30647671], dtype=DTYPE) arr_out = lnorm(arr_in, plugin=plugin, plugin_kwargs=plugin_kwargs) gv = arr_out[idx] assert_allclose(gv, gt, rtol=RTOL, atol=ATOL)
def test_strides_self(): arr_in = lena() / 1. arr_in = arr_in[:12, :12] arr_in.shape = arr_in.shape[:2] + (1,) neighborhood = 3, 3 for stride in xrange(1, 12): arr_out = lpool3(arr_in, neighborhood) gt = arr_out[::stride, ::stride] gv = lpool3(arr_in, neighborhood, stride=stride) assert_array_equal(gv, gt)
def __init__(self): self.numImages = 1 self.numPatches = 5000 self.sizePatches = 4#8 must be equal number, to be able to split in half later self.imageDataBase = [misc.lena()] self.patchDataBase = [] self.concImgArray = np.zeros((self.sizePatches*self.sizePatches,self.numPatches)) for i in range(self.numPatches): #should be random num randPosX = random.randint(self.sizePatches/2, self.imageDataBase[self.numImages-1].shape[0]-self.sizePatches/2) randPosY = random.randint(self.sizePatches/2, self.imageDataBase[self.numImages-1].shape[1]-self.sizePatches/2) self.patchDataBase.append(self.imageDataBase[self.numImages-1][randPosX-self.sizePatches/2:randPosX+self.sizePatches/2,randPosY-self.sizePatches/2:randPosY+self.sizePatches/2]) self.concatenateImages()
} """ inline(code, ['A', 'K', 'R', 'l', 'b', 'N', 'M', 'U', 'V', 'Z'], type_converters=converters.blitz, auto_downcast=0, **weave_options) A_ = np.dot(U, V) return A_ + mean #Rework of lena example #From https://gist.github.com/thearn/5424219 #Full matrix SVD, low rank approximation approx = K = 30 iterations = I = 10 A = np.asarray(lena(), dtype=np.double) A_ = lowrank_SVD(A, approx=K) plot.figure() plot.title("Low Rank SVD (full matrix) RMSE = ") plot.imshow(A_, cmap=cm.gray) #Sparse matrix setup sparseness = .85 A = lena() for i in xrange(len(A)): for j in xrange(len(A[i])): if np.random.rand() < sparseness: A[i, j] = 0. #Sparse lena plot.figure()
# See # http://www.mathworks.com/matlabcentral/fileexchange/41526-gray-scale-image-segmentation-using-normalized-graphcuts/ # for a similar implementation in MATLAB import matplotlib.pyplot as plt import numpy as np from scipy.linalg import eigh from scipy.misc import imresize """ # Downsized lena # Converted with imagemagick # convert -geometry 80x80 lenna.jpg lenna.jpg # im = plt.imread("lenna.jpg") """ from scipy.misc import lena im = lena() """ from scipy.misc import face im = face(gray=True) """ # Any bigger and my weak laptop gets memory errors bounds = (50, 50) im = imresize(im, bounds, interp="bicubic") """ from scipy.ndimage import zoom # zoom only works from 80 -> 50, not 512 -> 50 frac_x = bounds[0] / float(im.shape[0]) frac_y = bounds[1] / float(im.shape[1]) frac = (frac_x, frac_y) im = zoom(im, frac, order=1)
true_label[i]) if is_correct[i]: plt.title(msg, color='green') else: plt.title(msg, color='red') plt.axis('off') for j in range(nsteps): plt.subplot(h, w, i * 2 * w + 2 + 1 + j) plt.imshow(patches_left[i, j]) plt.axis('off') plt.subplot(h, w, i * 2 * w + 2 + 1 + j + w) plt.imshow(patches_right[i, j]) plt.axis('off') plt.show() plt.savefig(fname) if __name__ == '__main__': from scipy.misc import lena imgs = lena()[None, ...].repeat(3, axis=0) patches_left = lena()[None, None, :256].repeat(3, axis=0).repeat(5, axis=1) patches_right = lena()[None, None, 256:].repeat(3, axis=0).repeat(5, axis=1) true_label = np.array(['angry', 'angry', 'sad']) predicted_label = np.array(['sad'] * 3) visualizefacenet('lena.pdf', imgs, patches_left, patches_right, true_label, predicted_label) # vim: set ts=4 sw=4 sts=4 expandtab:
from scipy.misc import lena from pylab import imread from scipy.ndimage import gaussian_filter from stl_tools import numpy2stl, text2png """ Some quick examples """ A = lena() # load Lena image, shrink in half A = gaussian_filter(A, 1) # smoothing numpy2stl(A, "examples/Lena.stl", scale=0.1, solid=False) A = 256 * imread("examples/example_data/NASA.png") A = A[:, :, 2] + 1.0 * A[:, :, 0] # Compose RGBA channels to give depth A = gaussian_filter(A, 1) # smoothing numpy2stl(A, "examples/NASA.stl", scale=0.05, mask_val=5., solid=True) A = 256 * imread("examples/example_data/openmdao.png") A = A[:, :, 0] + 1. * A[:, :, 3] # Compose some elements from RGBA to give depth A = gaussian_filter(A, 2) # smoothing numpy2stl(A, "examples/OpenMDAO-logo.stl", scale=0.05, mask_val=1., min_thickness_percent=0.005, solid=True) text = ("$\oint_{\Gamma} (A\, dx + B\, dy) = \iint_{U} \left(\\frac{\partial " "B}{\partial x} - \\frac{\partial A}{\partial y}\\right)\ dxdy$ \n\n " "$\\frac{\partial \\rho}{\partial t} + \\frac{\partial}{\partial x_j}"
import numpy as np from oclutils import Ocl import matplotlib.pyplot as plt def myhist256(img): res = np.clip(img.astype(np.int32), 0, 255) h = np.histogram(res, bins=256, range=(0, 255)) return h[0] if __name__ == "__main__": from scipy.misc import lena img = lena().astype(np.int32) # ! Nr, Nc = img.shape # Initialize device ocl = Ocl(profile=True) print("running on %s" % ocl.devicename) # Build Program program = ocl.compile_file("opencl/histogram.cl") # Device memory d_input = ocl.to_device(img, flags="r") d_output = ocl.create_buffer_zeros(256, np.int32) # Execute wg = None
imgs = np.array(imgs) X = imgs[0].copy() P = nabla(X) Rs = np.zeros_like(imgs) for i in xrange(iter_n): P = project_nd(P + sigma * nabla(X), 1.0) Rs = np.clip(Rs + sigma * (X - imgs), -clambda, clambda) X1 = X - tau * (nablaT(P) + Rs.sum(0)) X = X1 + theta * (X1 - X) return X if __name__ == '__main__': import matplotlib.pyplot as plt from scipy.misc import lena img_ref = lena()[140:, 120:][:256, :256] / 255.0 def make_noisy(img): # add gaussian noise img = img + 0.1 * np.random.normal(size=img.shape) # add some outliers in on the right side of the image m = np.random.rand(*img.shape) < 0.2 m[:, :160] = 0 img[m] = np.random.rand(m.sum()) return img def make_spotty(img, r=3, n=1000): img = img.copy() h, w = img.shape for i in xrange(n): x, y = np.int32(np.random.rand(2) * (w - r, h - r))
#--- plot ------------------------------------------------------------------------------------------------------------- # ipy interactive plot spyder Tools>Preferences>Ipython Console>Graphics>Graphics Backend # plt.show(), weak win_upd; fig_window_update stopped working (need to resize win to update); plt.show(),spyder_restart did not help; from numpy import *; from matplotlib.pyplot import *; from scipy.misc import lena; # import numpy as np, matplotlib.pyplot as plt; from scipy.misc import lena; # plot,axis,lbl etc x=arange(0,2,.01); y=sin(2*pi*x); theta=arange(0,2*pi,0.001); r=sin(2*theta); clf(); subplot(211); plot(x,y,'g+'); subplot(212); semilogy(x,1.5+y,'r',linewidth=1); # semilogy(x,linewidth=1); loglog(x,y); scatter(x,y); polar(theta,r); axis([0,10,0,5]); text(2,.25,'t2'); xlabel('x1'); ylabel('y1'); title('a$^2$'); grid(1); # xlim,xticks; show(); ion(); ioff(); # interactive mode (worked before,not now?) clf(); hist(x**2,50); # contour,surface etc o=r_[-2:2:100j]; [x,y]=meshgrid(o,o); z=x*power(math.e,-x**2-y**2); clf(); contour(x,y,z,cmap=cm.gray,origin='lower',extent=(-3,3,-3,3)); im=imshow(z,interpolation='bilinear',origin='lower',extent=(-3,3,-3,3)); contour(); contourf(); colorbar(); quiver(x,z); # quiver - plot arrows clf(); imshow(lena(),cmap=cm.gray) # image_proc; cm only pseudo_color? d=random.rand(2,100)*512; scatter(d[0,:],d[1,:]); # clf(); hist(lena().flatten(),50); savefig('foo.pdf') # os.system('merge ...'); from matplotlib.backends.backend_pdf import PdfPages; pp=PdfPages('multipage.pdf'); pp.savefig(); pp.close(); # no '-append to fnm_existing' #--- numpy arrays ------------------------------------------------------------------------------------------------------ ###n=2; nt=5; a=[None]*n; b=np.zeros((n,nt)); b[:]=np.nan; c=np.zeros((n,nt),dtype=object); c[:]=None; # init list,vec,array NaN/None # ML_arrays pass-by-value semantics,slice_copy,lazy copy-on-write; # np.array pass-by-ref, slice_view(ptr); vec is 1d np.array; "usemask"~array_bool; np.array "go by row",ML "go by col" # single_ix[3],slice[2:5],ix_arr[1,2,4],mask_arr[T,T,F,T]; # visualization: (d1,d2,d3) d1-outer,(d2,d3); ML (d1,d2),d3 outer; # vec (array ndim=1) and array often behave differently; # array_column-major order ML,Fortran,R; array_row-maj C/cpp,py # array - row,col,page(3rd dim); array fn works on lists, not the opposite import numpy as np; from numpy import r_,c_,ix_; # np.matrix more ML-like,2D-only; to be avoided; n=3; nt=4; A=np.array([[1,2,3],[4,5,6]],dtype=np.float); A.astype('complex'); B=np.array([A,A,A,A]); # B is 3D
x = np.random.normal(size=(size, size, size)) y = np.random.normal(size=(3, size, size, size)) np.testing.assert_almost_equal(np.sum(gradient(x) * y), -np.sum(x * div(y))) if __name__ == '__main__': # First our test test_grad_div_adjoint() from scipy.misc import lena import matplotlib.pyplot as plt from time import time # Smoke test on lena l = lena().astype(np.float) # normalize image between 0 and 1 l /= l.max() l += 0.1 * l.std() * np.random.randn(*l.shape) t0 = time() res = tv_denoise_fista(l, weight=2.5, eps=5.e-5, verbose=True) t1 = time() print t1 - t0 plt.figure() plt.subplot(121) plt.imshow(l, cmap='gray') plt.subplot(122) plt.imshow(res, cmap='gray') # Smoke test on a 3D random image with hidden structure np.random.seed(42)
from scipy import misc import matplotlib.pyplot as plt import numpy as np import sys lena = misc.lena().astype(float)/255.0 noisy_mask = np.random.poisson(0.05, lena.shape) > 0 noisy_lena = np.array(lena) noisy_lena[noisy_mask] = 0 # print lena # print noisy_lena # print np.random.poisson(0.1, lena.shape).astype(float) fig = plt.figure() plt.gray() plt.subplot(121) plt.imshow(lena) plt.subplot(122) plt.imshow(noisy_lena) plt.show()
from scipy import misc import numpy as np import matplotlib.pyplot as plt from scipy import ndimage # (1) 载入Lena图像,并使用灰度颜色表将其在子图中显示出来。 image = misc.lena().astype(np.float32) plt.subplot(221) plt.title("Original Image") img = plt.imshow(image, cmap=plt.cm.gray) plt.axis("off") # 2) 中值滤波器扫描信号的每一个数据点,并替换为相邻数据点的中值。 plt.subplot(222) plt.title("Median Filter") filtered = ndimage.median_filter(image, size=(42,42)) plt.imshow(filtered, cmap=plt.cm.gray) plt.axis("off" ) # (3) 旋转图像并显示在第三个子图中。 plt.subplot(223) plt.title("Rotated") rotated = ndimage.rotate(image, 90) plt.imshow(rotated, cmap=plt.cm.gray) plt.axis("off") # (4) Prewitt滤波器是基于图像强度的梯度计算。对图像应用Prewitt滤波器并显示在第四个子图中 plt.subplot(224) plt.title("Prewitt Filter") filtered = ndimage.prewitt(image) plt.imshow(filtered, cmap=plt.cm.gray) plt.axis("off") plt.show()
dev.createImage(data.shape[::-1], mem_flags=cl.mem_flags.READ_WRITE, dtype=np.float32, channel_order=cl.channel_order.RGBA) for i in range(2) ] outImg = dev.createImage(data.shape[::-1], dtype=np.float32, mem_flags=cl.mem_flags.READ_WRITE) dev.writeImage(inImg, data.astype(np.float32)) dev.writeImage(pImgs[0], np.zeros((4, ) + data.shape, dtype=np.float32)) dev.writeImage(pImgs[1], np.zeros((4, ) + data.shape, dtype=np.float32)) for i in range(Niter): proc.runKernel("div_step", inImg.shape, None, inImg, pImgs[i % 2], outImg) proc.runKernel("grad_step", inImg.shape, None, outImg, pImgs[i % 2], pImgs[1 - i % 2], np.float32(weight)) return dev.readImage(outImg, dtype=np.float32) if __name__ == '__main__': from scipy.misc import lena d = lena() d = np.random.poisson(d, d.shape) res = bilateral2(d, 3, 100.)
""" Displaying Lena ================ Small example to plot lena. """ from scipy import misc l = misc.lena() misc.imsave('lena.png', l) # uses the Image module (PIL) import matplotlib.pyplot as plt plt.imshow(l) plt.show()
from __future__ import division from pylab import * from scipy.misc import lena, imresize from numpy import savetxt x = lena() #N = 2**9 #x = imresize(x, (N, N)) x = x / x.max() savetxt('input.csv', x, delimiter=',') show()
def transforms_1(): """ WIP image transforms collection. """ assert False, 'TODO' from PIL import Image, ImageEnhance image = Image.open('downloads/jcfeb2011.jpg') ## Sharpness - 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image: i2 = ImageEnhance.Sharpness(image).enhance(factor) ## An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image. i2 = ImageEnhance.Brightness(image).enhance(factor) ## An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image. i2 = ImageEnhance.Contrast(image).enhance(factor) ## An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image. i2 = ImageEnhance.Color(image).enhance(factor) ## Rotate, -180 to 180, resample=Image.NEAREST, resample=Image.BILINEAR, resample=Image.BICUBIC: i2 = i1.rotate(45) ## Rotate without cropping: i2 = i2.rotate(45, expand=True) ## Specify transparent color: transparency = im.info['transparency'] im.save('icon.gif', transparency=transparency) ## Crop off max 10% from each side: width, height = i1.size left = width / randint(10, 100) top = height / randint(10, 100) right = width - (width / randint(10, 100)) bottom = height - (height / randint(10, 100)) i2 = i1.crop((left, top, right, bottom)) ### http://pillow.readthedocs.io/en/3.1.x/reference/ImageOps.html ## cutoff – How many percent to cut off from the histogram. ignore – The background pixel value (use None for no background). PIL.ImageOps.autocontrast(image, cutoff=0, ignore=None) ## The black and white arguments should be RGB tuples; PIL.ImageOps.colorize(image, black, white) ## Remove border from image. The same amount of pixels are removed from all four sides. PIL.ImageOps.crop(image, border=0) ## Applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. PIL.ImageOps.equalize(image, mask=None) ## Add border to the image PIL.ImageOps.expand(image, border=0, fill=0) ## Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. PIL.ImageOps.fit(image, size, method=0, bleed=0.0, centering=(0.5, 0.5)) ## Convert the image to grayscale. PIL.ImageOps.grayscale(image) ## Reduce the number of bits for each color channel. PIL.ImageOps.posterize(image, bits) #### Perspective transformation: http://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil ####### ## http://cbio.ensmp.fr/~nvaroquaux/formations/scipy-lecture-notes/advanced/image_processing/index.html ## http://www.scipy-lectures.org/advanced/image_processing/ from scipy import ndimage from scipy import misc lena = misc.imread('lena.png') ### ## Cropping lena = misc.lena() lx, ly = lena.shape crop_lena = lena[lx / 4:-lx / 4, ly / 4:-ly / 4] ## up <-> down flip flip_ud_lena = np.flipud(lena) ## rotation rotate_lena = ndimage.rotate(lena, 45) rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False) ## Add noise to image: noisy = l + 0.4 * l.std() * np.random.random(l.shape) ## A Gaussian filter smoothes the noise out... and the edges as well: blurred_lena = ndimage.gaussian_filter(lena, sigma=3) very_blurred = ndimage.gaussian_filter(lena, sigma=5) ##A median filter preserves better the edges: med_denoised = ndimage.median_filter(noisy, 3) ##Total-variation (TV) denoising. Find a new image so that the total-variation of the image (integral of the norm L1 of the gradient) is minimized, while being close to the measured image: from skimage.filter import tv_denoise tv_denoised = tv_denoise(noisy, weight=50) ## Increase the weight of edges by adding an approximation of the Laplacian: filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1) alpha = 30 sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l)
from PIL import Image from scipy import misc from scipy import linalg, dot def transform(input_matrix, dim): print len(input_matrix) u, sigma, vt = linalg.svd(input_matrix) for index in xrange(dim, len(input_matrix)): sigma[index] = 0.0 return dot(dot(u, linalg.diagsvd(sigma, len(input_matrix), len(vt))), vt) lena = misc.lena() U, s, Vh = linalg.svd(lena) compressed = transform(lena, 64)
def setUp(self): self.image = testdata.prepare_image() self.lena = Image.fromarray(misc.lena())