Asif Khadir
Asif Khadir

Reputation: 39

How to change an image to grayscale represented as a NumPy array

Preface:

I have an image of a coin. This is any generic image of a coin that I plug into python, and I want to make this coin a grayscale image. The variable P represents the array containing the RGB values for the picture of the coin, and I believe that I can turn RGB to grayscale by changing any RGB values under 128 to 0 while turning any RGB values above 128 to 255.

Error:

I am trying to use a for loop to turn the values in the array generated by P to 0, 128, and 255. When I do so this way, I encounter the error as:

TypeError: '<' not supported between instances of 'tuple' and 'int' ".

Code:

import numpy as np
import matplotlib.pyplot as plt
P = plt.imread('coin.jpg')
for item in enumerate(P):
    if item < 128:
        item = 0
    elif item > 128:
        item = 255

Upvotes: 2

Views: 3393

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 207375

Two issues. Firstly, you are not converting to greyscale. Secondly, the whole point of numpy is to vectorise and avoid for loops because they are slow.

So starting with this image:

enter image description here

You want something like this:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Load coins and convert to greyscale
grey = np.array(Image.open('coins.png').convert('L'))

# Threshold at 128
thresholded=((grey>128)*255).astype(np.uint8)

# Save
Image.fromarray(thresholded).save('result.png')

enter image description here

Upvotes: 4

KaiserKatze
KaiserKatze

Reputation: 1569

Hereby I quote from Wikipedia:

Converting color to grayscale

Conversion of an arbitrary color image to grayscale is not unique in general; different weighting of the color channels effectively represent the effect of shooting black-and-white film with different-colored photographic filters on the cameras.

So, you need to implement an algorithm to convert original images into greyscale images, that is, to convert the tuples of color in RGB space you get from enumerate() to a tuple of color in greyscale space.

Then if you want to convert greyscale images into binary images, you need thresholding.

Thresholding (image processing)

Thresholding is the simplest method of image segmentation. From a grayscale image, thresholding can be used to create binary images.

Read more about Greyscaling:

Upvotes: 1

SuperKooks
SuperKooks

Reputation: 490

Sruthi V is right. enumerate() returns a tuple.

So instead of if item < 128 it should be if item[1] < 128

Or you could just remove enumerate() entirely if you aren't using it. It seems it will work fine without it.

Upvotes: 1

Related Questions