Skip to content Skip to sidebar Skip to footer

What's The Best Way To Greyscale In Python/django?

I want to greyscale my images that will be uploaded into django. So I found two ways, either opencv or imagemagick. And within imagemagick, imagemagickWand might be better because

Solution 1:

You can get nicer results if you convert to linear light first.

An sRGB image will have a gamma of about 2.4 applied to it, that is, there is more range in the bright areas than the dark. If you do 0.2 r + 0.7 g + 0.1 b directly on an sRGB image it can distort lightness relationships, for example:

enter image description here

From the left, those are the original image, a greyscale made by a simple recombination of sRGB, a greyscale made by a very fancy local adaptive algorithm, and a greyscale made in linear light. The linear light version keeps the red-blue difference better than the non-linear, though it doesn't look quite as nice as the adaptive version. You can read about the adaptive algorithm here.

Conversion to linear light can be done by a simple ungamma, if you are sure you have sRGB, or, better, by converting to XYZ using an ICC profile. pyvips has a linear-light greyscale conversion built in, try:

import pyvips

image = pyvips.Image.new_from_file("/home/john/pics/k2.jpg", access="sequential") 
image = image.colourspace("b-w")
image.write_to_file("x.jpg")

The advantages for vips over PIL or imagemagick would be better quality, faster, and much lower memory use. For a 10,000 x 10,000 pixel RGB JPEG, I see:

$ time ./magickwand.py 
real    0m2.613s
user    0m2.084s
sys 0m0.500s
peak RES 840MB
$ time ./vips.py
real    0m1.722s
user    0m5.716s
sys 0m0.116s
peak RES 54MB

That's on a two-core laptop.


Solution 2:

What's the best way to greyscale in python/django?

Take your pick.

ImageMagick's wand library

from wand.image import Image
with Image(filename='logo:') as img:
    img.colorspace = 'gray'
    img.save(filename='logo_gray.jpg')

Or CV2

import cv2
img = cv2.imread('example.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('example_gray.jpg',gray)

Both projects are mature, stable, and have a large community base. Try installing both libraries, and experimenting.

In the end grayscale is just (from wikipedia).

Y = 0.2126 * RED + 0.7152 * GREEN + 0.0722 * BLUE

Both do this well, and depend on delegates (i.e. libjpeg) to read & write image formats.


Post a Comment for "What's The Best Way To Greyscale In Python/django?"