user3014233
user3014233

Reputation:

How to use Pillow instead cv2?

I have a small histogram program on Python, I want to use Pillow library instead of cv2.

from PIL import Image
import cv2
import matplotlib.pyplot as plt
im = cv2.imread('pic.jpg')
im.ndim == 3:
        # Input image is three channels
        fig = plt.figure()
        fig.add_subplot(311)
        plt.hist(im[...,0].flatten(), 256, range=(0, 250), fc='b')
        fig.add_subplot(312)
        plt.hist(im[...,1].flatten(), 256, range=(0, 250), fc='g')
        fig.add_subplot(313)
        plt.hist(im[...,2].flatten(), 256, range=(0, 250), fc='r')
        plt.show()

I can replace im = cv2.imread('pic.jpg') to im = Image.open('pic.jpg') and im.ndim to im.getbands(), but what can i do with im[...,0].flatten()?

Upvotes: 1

Views: 8712

Answers (2)

Biplob Das
Biplob Das

Reputation: 3104

This is how to get pixel values (from 0 to 255) of an image using pillow:

from PIL import Image # import library
import numpy as np # import library

img = Image.open('myImage.png') # use Image.open(image_location)
image_data = np.array(img) # to convert img object to array value use np.array
print(image_data) # now, print all the pixel values of image in np array

Upvotes: 0

hitzg
hitzg

Reputation: 12711

In Python opencv uses numpy arrays as data structures for images. So cv2.imread returns a numpy array. Matplotlib has a similar function, so for the example in your question you need neither opencv nor pil:

import matplotlib.pyplot as plt
im = plt.imread('pic.jpg')
if im.shape[2] == 3:
    # Input image is three channels
    fig = plt.figure()
    fig.add_subplot(311)
    plt.hist(im[...,0].flatten(), 256, range=(0, 250), fc='b')
    fig.add_subplot(312)
    plt.hist(im[...,1].flatten(), 256, range=(0, 250), fc='g')
    fig.add_subplot(313)
    plt.hist(im[...,2].flatten(), 256, range=(0, 250), fc='r')
    plt.show()

If you have to use PIL to load the image, then you can convert it to a numpy array before plotting:

from PIL import Image
import numpy as np

im = np.array(Image.open('pic.jpg'))

Upvotes: 3

Related Questions