Posts

Showing posts with the label Image

Convert Np.array Of Type Float64 To Type Uint8 Scaling Values

Answer : A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2] , the code right now would scale that to have intensities of [0, 128, 255] . You want these to remain small after converting to np.uint8 . Therefore, divide every value by the largest value possible by the image type , not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type ( dtype ) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value. So with the above, do the following modifications to your code: import numpy as np import cv2 [...] info = np.iinfo(d...

Creating A PNG File In Python

Answer : Simple PNG files can be generated quite easily from pure Python code - all you need is the standard zlib module and some bytes-encoding to write the chunks. Here is a complete example that the casual reader may use as a starter for their own png generator: #! /usr/bin/python """ Converts a list of list into gray-scale PNG image. """ __copyright__ = "Copyright (C) 2014 Guido Draheim" __licence__ = "Public Domain" import zlib import struct def makeGrayPNG(data, height = None, width = None): def I1(value): return struct.pack("!B", value & (2**8-1)) def I4(value): return struct.pack("!I", value & (2**32-1)) # compute width&height from data if not explicit if height is None: height = len(data) # rows if width is None: width = 0 for row in data: if width < len(row): width = len(row) # generate these chunks...

Copy Image To Clipboard From Browser In Javascript?

Answer : No, you can't copy images to the clipboard. Copying anything to the clipboard is a security limitation of every browser, but you may able to copy text to the clipboard in IE if they have the proper security settings. Here Mozilla lists some of the problems caused by programmatic access to the clipboard. Yes, most of the scripts supports text only. http://forums.mozillazine.org/viewtopic.php?f=25&t=1195035&start=0 The above site also discussing the same issue. The following site said related to security issues, http://kb.mozillazine.org/Granting_JavaScript_access_to_the_clipboard but this won't work in latest version of Mozilla. The last answer is from 2010 and browsers have changed a lot since then. With this simple function, you can copy whatever you want (text, images, tables, etc) (on your page) to the clipboard. The function receive the element id or the element itself. function copyElementToClipboard(element) { window.getSelection().removeAllRanges...

CSS Image Overlay With Color And Transparency

Answer : CSS Filter Effects It's not fully cross-browsers solution, but must work well in most modern browser. <img src="image.jpg" /> <style> img:hover { /* Ch 23+, Saf 6.0+, BB 10.0+ */ -webkit-filter: hue-rotate(240deg) saturate(3.3) grayscale(50%); /* FF 35+ */ filter: hue-rotate(240deg) saturate(3.3) grayscale(50%); } </style> EXTERNAL DEMO PLAYGROUND CSS Filter Effects IN-HOUSE DEMO SNIPPET (source:simpl.info) #container { text-align: center; } .blur { filter: blur(5px) } .grayscale { filter: grayscale(1) } .saturate { filter: saturate(5) } .sepia { filter: sepia(1) } .multi { filter: blur(4px) invert(1) opacity(0.5) } <div id="container"> <h1><a href="https://simpl.info/cssfilters/" title="simpl.info home page">simpl.info</a> CSS filters</h1> <img src="https://simpl.info/cssfilters/balham.jpg" alt="No filter: B...

CSS Image Size, How To Fill, But Not Stretch?

Answer : You can use the css property object-fit . .cover { object-fit: cover; width: 50px; height: 100px; } <img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" /> See example here There's a polyfill for IE: https://github.com/anselmh/object-fit If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property. .container { width: 150px; height: 100px; background-image: url("http://i.stack.imgur.com/2OrtT.jpg"); background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; } <div class="container"></div>​ While cover will give you a scaled up image, contain will give you a scaled down image. Both will preserve the pixel aspect ratio. http://jsfiddle.net/uTHqs/ (using cover) http://jsfiddle.net/HZ2FT/ (using contain) This approach has the advantage ...

CSS Force Image Resize And Keep Aspect Ratio

Answer : img { display: block; max-width:230px; max-height:95px; width: auto; height: auto; } <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p> <img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png"> This will make image shrink if it's too big for specified area (as downside, it will not enlarge image). I've struggled with this problem quite hard, and eventually arrived at this simple solution: object-fit: cover; width: 100%; height: 250px; You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you. More information about the possible values for the object-fit property and a compatibility table are available here: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit Cheers. The solutions below will allow scaling up and scaling down of the image , depending on the parent box width. All images have a parent cont...

Android: Combining Text & Image On A Button Or ImageButton

Answer : For users who just want to put Background, Icon-Image and Text in one Button from different files: Set on a Button background, drawableTop/Bottom/Rigth/Left and padding attributes. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/home_btn_test" android:drawableTop="@drawable/home_icon_test" android:textColor="#FFFFFF" android:id="@+id/ButtonTest" android:paddingTop="32sp" android:drawablePadding="-15sp" android:text="this is text"></Button> For more sophisticated arrangement you also can use RelativeLayout (or any other layout) and make it clickable. Tutorial: Great tutorial that covers both cases: http://izvornikod.com/Blog/tabid/82/EntryId/8/Creating-Android-button-with-image-and-text-using-relative-layout.aspx There's a mu...

Alternative Segmentation Techniques Other Than Watershed For Soil Particles In Images

Image
Answer : You could try using Connected Components with Stats already implemented as cv2.connectedComponentsWithStats to perform component labeling. Using your binary image as input, here's the false-color image: The centroid of each object can be found in centroid parameter and other information such as area can be found in the status variable returned from cv2.connectedComponentsWithStats . Here's the image labeled with the area of each polygon. You could filter using a minimum threshold area to only keep larger polygons Code import cv2 import numpy as np # Load image, Gaussian blur, grayscale, Otsu's threshold image = cv2.imread('2.jpg') blur = cv2.GaussianBlur(image, (3,3), 0) gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # Perform connected component labeling n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=4) # Create fal...

Convert Tiff To Jpg In Php?

Answer : In the forum at http://www.php.net/gd the following comment is written: IE doesn't show TIFF files and standard PHP distribution doesn't support converting to/from TIFF. ImageMagick (http://www.imagemagick.org/script/index.php) is a free software that can read, convert and write images in a large variety of formats. For Windows users it includes a PHP extension php_magickwand_st.dll (and yes, it runs under PHP 5.0.4). When converting from TIFF to JPEG, you must also convert from CMYK color space to RGB color space as IE can't show CMYK JPGs either. Please note: -TIFF files may have RGB or CMYK color space -JPEG files may have RGB or CMYK color space Here are example functions using ImageMagick extension: - convert TIFF to JPEG file formats - convert CMIK to RGB color space - set image resolution to 300 DPIs (doesn't change image size in pixels) <?php function cmyk2rgb($file) { $mgck_wnd = NewMagickWand(); MagickReadImage($mgck_wnd, $file); $im...

Android Emulator Camera Custom Image

Image
Answer : Under Tools > AVD Manager , select the "pencil" to get to "Virtual Device Configuration". Show Advanced Settings > Camera will give you the option of using emulated, or a device: Device - use host computer webcam or built-in camera If all you need is to get a still image into the camera, starting with Android Studio 3.2 you can put your static images into the virtual scene: as discussed in this entry from Android developers blog. Note that you'll need to move the camera position into the dining room to see your images (turn around and use Alt-w to move forward). Finally! Append to file ~/Android/Sdk/emulator/resources/Toren1BD.posters poster custom size 2 2 position 0 0 -1.8 rotation 0 0 0 default custom.png Place 'custom.png' in ~/Android/Sdk/emulator/resources/ Restart! emulator @Phone -no-snapshot -no-boot-anim (replace 'Phone' with the name of your avd! (see: emulator -list-avds) Profit! Now you have a...

100x100 Image With Random Pixel Colour

Image
Answer : This is simple with numpy and pylab . You can set the colormap to be whatever you like, here I use spectral. from pylab import imshow, show, get_cmap from numpy import random Z = random.random((50,50)) # Test data imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest') show() Your target image looks to have a grayscale colormap with a higher pixel density than 100x100: import pylab as plt import numpy as np Z = np.random.random((500,500)) # Test data plt.imshow(Z, cmap='gray', interpolation='nearest') plt.show() If you want to create an image file (and display it elsewhere, with or without Matplotlib), you could use NumPy and Pillow as follows: import numpy, from PIL import Image imarray = numpy.random.rand(100,100,3) * 255 im = Image.fromarray(imarray.astype('uint8')).convert('RGBA') im.save('result_image.png') The idea here is to create a numeric array, convert it to a RGB image, and sa...

Android: Picasso Load Image Failed . How To Show Error Message

Answer : Use builder: Picasso.Builder builder = new Picasso.Builder(this); builder.listener(new Picasso.Listener() { @Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { exception.printStackTrace(); } }); builder.build().load(URL).into(imageView); Edit For version 2.71828 they have added the exception to the onError callback: Picasso.get() .load("yoururlhere") .into(imageView, new Callback() { @Override public void onSuccess() { } @Override public void onError(Exception e) { } }) When you use callback, the picaso will call method onSuccess and onError! File fileImage = new File(mPathImage); Picasso.with(mContext).load(fileImage) .placeholder(R.drawable.draw_detailed_view_display) .error...

Convert RGBA To RGB In Python

Answer : You probably want to use an image's convert method: import PIL.Image rgba_image = PIL.Image.open(path_to_image) rgb_image = rgba_image.convert('RGB') In case of numpy array, I use this solution: def rgba2rgb( rgba, background=(255,255,255) ): row, col, ch = rgba.shape if ch == 3: return rgba assert ch == 4, 'RGBA image has 4 channels.' rgb = np.zeros( (row, col, 3), dtype='float32' ) r, g, b, a = rgba[:,:,0], rgba[:,:,1], rgba[:,:,2], rgba[:,:,3] a = np.asarray( a, dtype='float32' ) / 255.0 R, G, B = background rgb[:,:,0] = r * a + (1.0 - a) * R rgb[:,:,1] = g * a + (1.0 - a) * G rgb[:,:,2] = b * a + (1.0 - a) * B return np.asarray( rgb, dtype='uint8' ) in which the argument rgba is a numpy array of type uint8 with 4 channels. The output is a numpy array with 3 channels of type uint8 . This array is easy to do I/O with library imageio using imread and imsave .

Converting A PDF To PNG

Answer : You can use one commandline with two commands ( gs , convert ) connected through a pipe, if the first command can write its output to stdout, and if the second one can read its input from stdin. Luckily, gs can write to stdout ( ... -o %stdout ... ). Luckily, convert can read from stdin ( convert -background transparent - output.png ). Problem solved: GS used for alpha channel handling a special image, convert used for creating transparent background, pipe used to avoid writing out a temp file on disk. Complete solution: gs -sDEVICE=pngalpha \ -o %stdout \ -r144 cover.pdf \ | \ convert \ -background transparent \ - \ cover.png Update If you want to have a separate PNG per PDF page, you can use the %d syntax: gs -sDEVICE=pngalpha -o file-%03d.png -r144 cover.pdf This will create PNG files named page-000.png , page-001.png , ... (Note that the %d -counting is zero...