Matplotlib changes channels of image when saving - image

I am using matplotlib to read an image, but the number of channels changes after I save the original image with imsave. Here is the code:
import matplotlib.image as mpimg
img = mpimg.imread('sample.tiff')
print(img.shape)
mpimg.imsave('sample2.tiff', img)
img2 = mpimg.imread('sample2.tiff')
print(img2.shape)
And here is the output:
(2160, 2160)
(2160, 2160, 4)
The image becomes a 4-channel image while it was 1-channel originally. And it seems that the final channel is always 255.
What is happening here? And the original image looks meaning less as it is all black. But when I read & save it with imread and imsave, I can finally see some meaningful figures.

The input image sample.tiff is a one channel gray scale image. One cannot know why that is the case, it simply depends on where you got that image from.
imread converts this image to a 2D numpy array.
When given a 2D numpy array as input imsave will apply a colormap to the array, and, without further arguments given, apply a normalization between the minimum and maximum data value. The resulting image is hence a color image with 4 channels.
imread then converts this image to a 3D numpy array.

It looks like you are not the first person to have this problem - see here.
My suggestion would be to use imageio (or PIL) to save the image (in fact, to read it too) and it works fine:
import imageio
import matplotlib.image as mpimg
img = mpimg.imread('a.tif')
imageio.imwrite('result.tif',img)

Related

How to create a 1 pixel white .gif from code only

I'm new to programming, i won't become a developer but I like to learn a few stuff, since i'm a creative artist. I'm trying to solve an exercise I came up with.
I'm looking for guidelines to create a 1 pixel image from code. I want to try to create the most basic form of a white image, and I thought that a lossless 1 pixel gif of white (#FFFFFF or RGB 255, 255, 255) could be the simplest form, generating the smallest code possible.
Where would I even start?
I created two 1 pixel white .gifs, one in Paint and another in Photoshop, using 8bit Grayscale color mode. Gave both of them the same name, and when I hash them, both hashes are different, so they are not exactly the same. I also tried exporting from photoshop twice, to different directories, and this time hashes are the same.
My intention is to create the simplest and purest form of that white pixel.
Tips?
In Python, you can use PIL to create an image. Here is the code for what you requested.
from PIL import Image # import library
img = Image.new(mode = "RGB", size = (1,1)) # creates a RGB image with the size of 1x1
pixels = img.load() # Creates the pixel map
pixels[0,0] = (255,255,255) # Set the colour of the first (and only) pixel to white
img.save(format='GIF', fp='./test.gif')
# Saves the image as a GIF in a file called test.gif in your current directory
The purest, simplest form that is widely readable (GIMP, Photoshop, MS-Paint) is NetPBM IMHO.
Here is a single white pixel - no metadata, no copyright, no EXIF, no creation date, no palette, no checksum. You can create it with a text editor or code:
P1
1 1
0
Save it as white.pbm
If you want a simple, single, red pixel, save the following as red.ppm:
P3
1 1
255
255 0 0
The simplest Python to create a white single pixel GIF with PIL is probably:
from PIL import Image
Image.new('L', (1,1), 255).save('white.gif')
The simplest Python to create a red single pixel GIF with PIL is probably:
from PIL import Image
Image.new('RGB', (1,1), 'red').save('red.gif')

How to draw single pixels in python Pillow from Numpy arrays without producing pixel noise?

I am stuck with a basic problem to which I was not able to find any answer nor solution no matter what I tried. Please help me out and enlighten me, what I am doing wrong :-)
Task:
Make a Numpy array of Pixels, manipulate them by an algorithm and then print an image from that array.
Occuring Problem:
When I manipulate single pixels this way, there is noise artifacts appearing next to manipulated pixels (see example pictures)
Details - What I want to do:
I have a numpy array to create an image from.
The array is created as black:
shape = np.zeros((100, 100, 3), dtype=np.uint8)
Now I want to manipulate single pixels by an algorithm, for instance:
color = (255, 255, 255)
shape[50, 50] = color
There will be 100s and 1000s of pixels manipulated in color this way.
At the end, I want to make an image from that shape array and print it to the screen:
arr_image = Image.fromarray(shape, 'RGB')
arr_image.save('test.jpg')
Details - What I tried:
No matter, what I do, I get pixel noise next to created pixels in images created using the example code!
I tried:
Searching the Internet/Stackoverflow: No such problem described/found
Taking working code from other examples and manipulate to my needs: Same artifacts occuring after manipulation
Drawing pixels in the created image after making a black-only (0,0,0) image from a numpy array by using Image method putpixel: Same artifacts appearing
Changing up syntax: Same artifacts appearing
Checking the underlying numpy arrays for grey values at the position of the artifacts: THERE IS NO SUCH GREY VALUES IN THE ARRAYS!!
When using Pillow method show(), the pixel noise is gone (!) in the windows popup, however (!!!), when I open the image from outside python, the pixel noise is in the exact same image visible (!!!!!!!!!!!!!)
Example code that produces this problem:
import numpy as np
from PIL import Image
shape = np.zeros((100, 100, 3), dtype=np.uint8)
white = (255, 255, 255)
shape[50][50] = white
arr_image = Image.fromarray(shape, 'RGB')
# arr_image.putpixel((50, 50), white)
arr_image.save('test.jpg')
Example images:
Black Array
[Same Array, but point 50][50] is set to white
[Same Array, but 100 random points were placed at x][y] and set to white
The solution to this is: Do not use .jpg data, the compression of this format causes observed pattern.
When using .png, the bug was instantly solved! In this image (.png), you can now see that there is 0 pixel noise nor strange artifact patterns, when generating an array-based image as described above: enter image description here
Thank you #dantechguy and #Mark Setchell, you guys saved me! :-))

Using PIL (Pillow) and Image but keeping a good resolution

I'm using PIL to resize my images. Most of them are 640x480, some of them are bigger. Most of them are in png, but I have jpeg extension too.
I want to resize all my images to be 32x32 pixels, but I noticed that the resolution seems to change after using PIL.
I found that is a typical question and It's often a problem that figure out when you are saving the image.
I tried with different values of "quality", I read the documentation trying different parametres such as "subsampling" and trying both jpeg and png format.
Here is my code:
from PIL import Image
im = Image.open(os.path.join(my_path, file_name))
img = im.resize((32, 32))
if grey_scale is True:
img = img.convert('L') # to resize image in gray scale
img.save(os.path.join(my_path,
file_name[:file_name.index('.')] + '.jpg'), "JPEG", quality=100)
Here I have my input image
Here I have the grainy output obtained with my code
How can I resize my images to be smaller, but keeping a very good resolution?
The sort of image transformation you want is not possible. As when you try to resize an raster image to a lower pixel dimensions, you have to either Downsample it, or not sample it at all(simple resize). Even though you may preserve the resolution (total no of pixels in an image) but still since a pixel can represent one color at a time (atleast in a sub-pixel based display like a monitor), and your final image only has 1024 of them, and the detail in the original image is far more then what could be represented by these number of pixels, this would always result in a considerably lower quality(pixelated image with artifacts) in the final image.
But this is not the general case, as it depends a lot on what sort of details are represented by the image. If the image is not complex (not contains a lot of color changes), then it can be resized to a considerably lower quality version of it without losing details.
746x338 dimension image
32x32 dimension version of previous image
There is almost no difference between both the images (except for their physical size), even though their dimension's are a lot different. The Reason being these are non-complex images containing same pixel value over a large range, which makes it easier to resize them without loss in detail.
Now if the same process is tried out on a complex image, like the one you gave in the question, the result would be an Pixelated image.
SOLUTION:-
You can either choose for a large dimension value in the final image
(a lot more then 32x32) if you want to preserve the image quality.
Create a Vector equivalent of your image, which is resolution
independent and can be resized to a larger/smaller physical size
without affecting image quality.
P.S.:-
Don't save a .png image with .jpgextension, as jpg is a lossy compression technique(for the most part), which in turn results in a lower quality final image, then the original even if no manipulation are made over it.
Reducing the size, you can't keep the image crisp, because you need pixels for those and you can't keep both
There are different filters you can use in this case. See the below code
from PIL import Image
import os
import PIL
filters = [PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.ANTIALIAS]
grey_scale = False
i = 0
for filter in filters:
im = Image.open("./image.png")
img = im.resize((32, 32), filter)
if grey_scale is True:
img = img.convert('L') # to resize image in gray scale
i = i + 1
img.save("./" + str(i) + '.jpg', "JPEG", quality=100)
Results:
Next, using resize you don't maintain the aspect ratio. So instead of using resize, use the thumbnail method which keeps aspect ratio as well
from PIL import Image
import os
import PIL
filters = [PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.ANTIALIAS]
grey_scale = False
i = 5
for filter in filters:
im = Image.open("./image.png")
img = im.thumbnail((32, 32), filter)
img = im
if grey_scale is True:
img = img.convert('L') # to resize image in gray scale
i = i + 1
img.save("./" + str(i) + '.jpg', "JPEG", quality=100)
Results:

Extracting pixel values using Pillow - every coordinate I use gives the same value

I am attempting to use the Pillow library in Python 2.7 to extract pixel values at given coordinates on PNG and JPG images. I don't get an errors but I always get the same value irrespective of the coordinates I have used on an image where the values do vary.
This is an extract from my script where I print all the values (its a small test image):
from PIL import Image
box = Image.open("col_grad.jpg")
pixels = list(box.getdata())
print(pixels)
And from when I try to extract a single value:
from PIL import Image, ImageFilter
box = Image.open("col_grad.jpg")
value = box.load()
print(value[10,10])
I have been using these previous questions on this topic for guidance including:
Getting list of pixel values from PIL
How can I read the RGB value of a given pixel in Python?
Thanks for any help with this,
Alex
I'm not sure if you can access it the way you want, because of the complexity of images data.
Just get the pixel:
Image.getpixel(xy)
Returns the pixel value at a given position.
Parameters: xy – The coordinate, given as (x, y).
Returns: The pixel value. If the image is a multi-layer image, this method returns a tuple.:
You should consider doing one of the following:
FIRST convert your image to grayscale and then find the pixel values present.
img_grey= img.convert('1') # convert image to black and white
SECOND If you want the pixel values of RGB channels, you have to split your color image. Then find the pixel values in all the channels at a particular coordinate.
Image.split(img)

Resizing ROI in an image

I have a 565 * 584 image as shown
I want to reduce the radius of the circle by certain number of pixels without changing the size of the image. How can I do it? Please explain or give some ideas. Thank You.
I would use ImageMagick and an erosion like this:
convert http://i.stack.imgur.com/c8lfe.jpg -morphology erode octagon:8 out.png
If you know that the background of the image is a constant, as in your example, this is easy.
Resize the entire image by the ratio you wish to shrink by. Then create a new image at the size of the original and fill it with the background color, then paste the resized image into the center of it.
Here's how you'd do it in OpenCV Python. Going with Mark Setchell's approach, simply specify a round structuring element so that you can maintain or respect the round edges of the object. The closest thing that OpenCV has to offer is the elliptical mask.
As such:
import numpy as np # Import relevant packages - numpy and OpenCV
import cv2
# Read in image and threshold - convert to grayscale first
im = cv2.imread('c8lfe.jpg', 0) > 128
# Specify radius of ellipse
radius = 21
# Obtain structuring element, then erode image
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius, radius))
# Make sure you convert back to grayscale and multiply by 255
out = 255*(cv2.erode(im, se).astype('uint8'))
# Show the image, wait for user key, then close window and write image
cv2.imshow('Reduced shape', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('out.png', out)
We get:
Be advised that the small bump at the top right corner of your shape will mutate. As we are essentially shrinking the perimeter of the object, that bump will also shrink as well. If you wish to preserve the structure of the object while maintaining the image resolution, use Mark Ransom's approach or my slightly modified version of his approach. Both are shown below.
However, to be self-contained, we can certainly do what Mark Ransom has suggested. Resize the image, initialize a blank image that is size of the original image, and place it in the centre:
import numpy as np # Import relevant packages - OpenCV and Python
import cv2
im = cv2.imread('c8lfe.jpg', 0) # Read in the image - grayscale
scale_factor = 0.75 # Set scale factor - We are shrinking the image by 25%
# Get the desired size (row and columns) of the shrunken image
desired_size = np.floor(scale_factor*np.array(im.shape)).astype('int')
# Make sure desired size is ODD for easier placement
if desired_size[0] % 2 == 0:
desired_size[0] += 1
if desired_size[1] % 2 == 0:
desired_size[1] += 1
# Resize the image. Columns come first, followed by rows, which is why we
# reverse the desired_size array
rsz = cv2.resize(im, tuple(desired_size[::-1]))
# Determine half width of both dimensions of shrunken image
half_way = np.floor(desired_size/2.0).astype('int')
# Create output image that is the same size as the input and find its centre
out = np.zeros_like(im, dtype='uint8')
centre = np.floor(np.array(im.shape)/2.0).astype('int')
# Place shrunken image in the centre of the larger output image
out[centre[0]-half_way[0]:centre[0]+half_way[0]+1, centre[1]-half_way[1]:centre[1]+half_way[1]+1] = rsz
# Show the image, wait for user key, then close window and write image
cv2.imshow('Reduced shape', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('out.png', out)
We get:
Another suggestion
What I can also recommend you do is pad the array with zeroes, then reshrink the image back to its original size. You would essentially extend the borders of the original image so that the borders contain zeroes. In this case, we would do what Mark Ransom also suggested, but we are working within the inside, out.
Here's the way to pad a matrix with zeroes using OpenCV C++: Pad array with zeros- openCV . However, in Python, simply use numpy's pad function:
import numpy as np # Import relevant packages - numpy and OpenCV
import cv2
# Read in image and threshold - convert to grayscale first
im = cv2.imread('c8lfe.jpg', 0)
# Set how many pixels along the border you want to add on each side
pad_radius = 75
# Pad the image
out = np.lib.pad(im, ((pad_radius, pad_radius), (pad_radius, pad_radius)), 'constant', constant_values=((0,0),(0,0)))
# Shrink it back to what the original size was
out = cv2.resize(out, im.shape[::-1])
# Show the image, wait for user key, then close window and write image
cv2.imshow('Reduced shape', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('out.png', out)
We thus get:

Resources