Skip to content

Incorrect Grayscale Conversion #3800

@Queuecumber

Description

@Queuecumber

What did you do?

I'm having a weird inconsistency in the way Pillow is treating grayscale images, and the difference is enough to throw off some metrics I need to compute. After a lot of debugging I was able to trace the inconsistency back to the grayscale conversion. I have included a comparison with OpenCV which I have verified to be the correct conversion. By correct conversion I mean one that is consistent with other programs I have tried (they all agree with OpenCV)

It is very hard to detect this difference by just looking at the grayscale ouputs but I am including them for completeness. The difference becomes extremely apparent under aggressive JPEG compression.

Pillow Output (verified wrong)

pillow_output

OpenCV Output (verified correct)

opencv_output

Difference

diff

Here is the code used to compute these images:

im = np.asarray(Image.open(args.input).convert('L'))
im2 = cv2.cvtColor(cv2.imread(args.input), cv2.COLOR_BGR2GRAY)

diff = im - im2

cv2.imwrite('pillow_output.png', im)
cv2.imwrite('opencv_output.png', im2)
cv2.imwrite('diff.png', diff)

Things to Note

  • This difference is only apparent when I do a grayscale conversion. If I leave the images as color images they are identical
  • OpenCV loads the images as BGR so line 2 is not a typo
  • Maybe this is related to a difference in the chosen luma transform?

What are your OS, Python and Pillow versions?

  • OS: Various Linux
  • Python: 3.5 and 3.6
  • Pillow: 6.0.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions