How about doing it with Pillow:
from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
If an alpha (transparency) channel is present in the input image and should be preserved, use mode LA:
img = Image.open('image.png').convert('LA')
Using matplotlib and the formula
Y' = 0.2989 R + 0.5870 G + 0.1140 B
you could do:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
img = mpimg.imread('image.png')
gray = rgb2gray(img)
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
plt.show()
Answer from unutbu on Stack OverflowHow about doing it with Pillow:
from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
If an alpha (transparency) channel is present in the input image and should be preserved, use mode LA:
img = Image.open('image.png').convert('LA')
Using matplotlib and the formula
Y' = 0.2989 R + 0.5870 G + 0.1140 B
you could do:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
img = mpimg.imread('image.png')
gray = rgb2gray(img)
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
plt.show()
You can also use scikit-image, which provides some functions to convert an image in ndarray, like rgb2gray.
from skimage import color
from skimage import io
img = color.rgb2gray(io.imread('image.png'))
Notes: The weights used in this conversion are calibrated for contemporary CRT phosphors: Y = 0.2125 R + 0.7154 G + 0.0721 B
Alternatively, you can read image in grayscale by:
from skimage import io
img = io.imread('image.png', as_gray=True)
How do I convert from grayscale to black and white?
Convert RGB Image to Grayscale and Display It (Python + Matplotlib) - Signal Processing Stack Exchange
Converting RGBA image to Gray scale and then binary
Converting Grayscale to Color Image using Color Maps
Videos
Consider the following image:
Image
If you zoom in, you will observe that the picture contains pixels of the form (0,0,0,x) in RGBA format (I have used pillow to verify this btw). What I want to do is if the pixel's alpha is less than equal to 200, then write (0,0,0,0) at the pixel's place, and if it is greater than 200 then write (0,0,0,255) at the pixel's place.
Here's my code rn:
from PIL import Image
import numpy as np
def inp_gen(img_path):
im = Image.open(img_path, 'r')
pix_vals = list(im.getdata())
layer = [x[3] for x in pix_vals]
for j in layer:
if j <= 200:
layer[layer.index(j)] = 0
if j > 200:
layer[layer.index(j)] = 1
return layer
def render_img(img_data):
image_data = [(0,0,0,255*x) for x in img_data]
data = np.array(image_data, dtype=np.uint8).T
image = Image.fromarray(data)
image.show()
render_img(img_gen("Path to image in drive link on my PC"))Sadly, this does not give me the output I want:
Output
So what should I do now?