wand.Image object to PIL Image - python

I currently have an image in the wand.image format. I need to convert it to PIL format so that I can continue working with it. It is and RGB image. I cant seem to find anywhere how to do it. I have tried to convert it to an np array and then read the np array into the PIL image. Thank you for any help. Here is my code if it helps:
from PIL import Image, ImageFilter
from wand.image import Image as Image2
with Image2(filename=join(img_path,file)) as img:
img.virtual_pixel = 'transparent'
test_image = Image.fromarray(np.array(img), 'RGB')

data_image = Image.open(io.BytesIO(img.make_blob("png"))).convert('RGB') fixes the issue for some reason

Related

Saving grayscale image to a directory in python

I have a piece of code that takes in image data as grayscale values, and then converts into an image using matplotlib below
import matplotlib.pyplot as plt
import numpy
image_data = image_result.GetNDArray()
numpy.savetxt('data.cvs', image_data)
# Draws an image on the current figure
image = plt.imshow(image_data, cmap='gray')
I want to be able to export this data to LabView as a .png file. So I need to save these image to a folder where LabView and display them. Is there a function with pillow or os that can do this?
plt.imsave('output.png', image)
Does this work?
If image_data is a Numpy array of shape height x width with dtype=np.uint8 or dtype=np.uint16, you can make a PIL Image and save it as a PNG like this:
from PIL import Image
# Make PIL Image from Numpy array
pImage = Image.fromarray(image_data)
pImage.save('forLabView.png')
You can equally use OpenCV to save a Numpy array as a PNG for LabView like this:
import cv2
# Save Numpy array as PNG
cv2.imwrite('forLabView.png', image_data)
Check what your array is with:
print(image_data.shape, image_data.dtype)

Skimage.io.read imread a PIL Object

So I was working with skimage for some image preprocessing (i'm very new to it). I have a PIL Image object and wanted to convert to a skimage image with skimage.io.imread(). I know that I can just save the image and then run imread on that file, but I was wondering if there was a way I could read the PIL Image object from the code itself. I tried to run imread on the PIL Image object itself but I end up getting errors.
OSError: Cannot understand given URI: <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=192....
Anyone know how I can solve this in skimage.
Scikit-Image stores images as Numpy arrays, so you just need to make a Numpy array from your PIL Image:
ImageForScikit = np.array(YourPILImage)
You may review imageio documentation related to the function imread for including in your code the attribute format and code as follows just in case the image format is PNG: imageio.imread(filename, format = 'PNG')

How to preserve the original colors of an image after adding text to it using PIL Python?

I am trying to add some text on my image using PIL, see the code below,
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import sys
image = Image.open('image.png')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial',40)
draw.text((700, 470),'Text',(0,0,0),font=font)
img.save('out-image.png','PNG')
But I lost the original colors of the image, see below images,
Original Image
After adding text
How I can preserve the original colors.
Thank You
That looks like a bug in PIL to me. I think it is because your image is palettised and the draw.text() is messing up the palette.
For a work-around, you can convert to an RGB image when you open it to avoid palette issues. Change to this:
image = Image.open('image.png').convert('RGB')

Convert opencv image format to PIL image format?

I want to convert an image loaded
TestPicture = cv2.imread("flowers.jpg")
I would like to run a PIL filter like on the example with the variable
TestPicture
but I'm unable to convert it back and forth between these types.
Is there a way to do these conversions?
Can OpenCV do all of the image filters that are in the PIL package?
Example:
Result:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold_img = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
im_pil = cv2_to_pil(threshold_img)
pytesseract.image_to_string(im_pil)
Out[5]: 'TUM'
Yes OpenCV is more robust and flexible and can perform most of the image processing routines which are available out there, So probably this filter can be done with OpenCV> However, there may not be a straightforward API for that.
Anyways, as far as the conversion of image format from OpenCV to PIL is concerned you may use Image.fromarray as:
import cv2
import numpy as np
from PIL import Image
img = cv2.imread("path/to/img.png")
# You may need to convert the color.
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(img)
# For reversing the operation:
im_np = np.asarray(im_pil)
But you must keep in mind that, OpenCV follows BGR convention and PIL follows RGB color convention, so to keep the things consistent you may need to do use cv2.cvtColor() before conversion.
Pillow and OpenCV use different formats of images. So you can't just read an image in Pillow and manipulate it into an OpenCV image.
Pillow uses the RGB format as #ZdaR highlighted, and OpenCV uses the BGR format. So, you need a converter to convert from one format to another.
To convert from PIL image to OpenCV use:
import cv2
import numpy as np
from PIL import Image
pil_image=Image.open("demo2.jpg") # open image using PIL
# use numpy to convert the pil_image into a numpy array
numpy_image=numpy.array(pil_img)
# convert to a openCV2 image, notice the COLOR_RGB2BGR which means that
# the color is converted from RGB to BGR format
opencv_image=cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)
To convert from OpenCV image to PIL image use:
import cv2
import numpy as np
from PIL import Image
opencv_image=cv2.imread("demo2.jpg") # open image using openCV2
# convert from openCV2 to PIL. Notice the COLOR_BGR2RGB which means that
# the color is converted from BGR to RGB
color_converted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)
pil_image=Image.fromarray(color_converted)
Here are two functions to convert image between PIL and OpenCV:
def toImgOpenCV(imgPIL): # Conver imgPIL to imgOpenCV
i = np.array(imgPIL) # After mapping from PIL to numpy : [R,G,B,A]
# numpy Image Channel system: [B,G,R,A]
red = i[:,:,0].copy(); i[:,:,0] = i[:,:,2].copy(); i[:,:,2] = red;
return i;
def toImgPIL(imgOpenCV): return Image.fromarray(cv2.cvtColor(imgOpenCV, cv2.COLOR_BGR2RGB));
Convert from OpenCV img to PIL img will lost transparent channel. While convert PIL img to OpenCV img will able to keep transparent channel, although cv2.imshow not display it but save as png will gave result normally.

How do I change my image format?

I'm trying to blur an image using PIL:
from PIL import Image
from PIL import ImageFilter
im = Image.open("plot.png")
im = im.filter(ImageFilter.BLUR)
When I do im.show() and save it to my hard drive, it saves as a BMP file, which is incompatible with the place where I'm trying to upload it. How do I change the file format from BMP to something else that is compatible?
Just use the save() function directly:
from PIL import Image
from PIL import ImageFilter
im = Image.open("plot.png")
im = im.filter(ImageFilter.BLUR)
im.save("saved.jpg")
This function supports many formats, as explained in the documentation.

Categories

Resources