image-processing icon indicating copy to clipboard operation
image-processing copied to clipboard

Automatic color scaling of matplotlib imshow for gray images

Open iimog opened this issue 1 year ago • 2 comments

When plt.imshow is used on a single channel image, a color scale is automatically applied. This can lead to surprising results, as the default color scheme is viridis and scales from blue to yellow. Therefore, throughout the lesson, the cmap is set to "gray" in those cases. That makes sense, but the results can still be surprising, as the default range is based on the minimum and maximum value that occurs in the image. This is best demonstrated with the sudoku challenge in the "Working with skimage" lesson. Trying to solve it with this code:

image = skimage.io.imread(fname="data/sudoku.png", as_gray=True)
image[image > 0.5] = 0.5
fig, ax = plt.subplots()
plt.imshow(image, cmap="gray")

yields this result image as the highest value in the whole image is now at 0.5 this value is mapped to white. This can be fixed by adding the vmax parameter to plt.imshow:

fig, ax = plt.subplots()
plt.imshow(image, cmap="gray", vmax=1)

now the result looks as expected image

I propose to add a box, explaining the vmin and vmax parameters and incorporating them into the solution of the sudoku challenge. If this is agreed upon, I'm happy to prepare a pull request :smiley:

PS: I taught this lesson a couple of weeks ago together with @CaptainSifff. I really enjoyed doing it. The lesson material is already really good. Great work!

iimog avatar Oct 13 '22 12:10 iimog

Thanks for catching that discrepancy. I am sure your proposed callout box and adjustment would be a most welcome pull request, and thank you for taking the time to field test the curriculum. That is also much appreciated.

As long as you are already modifying that exercise. I noticed the following potential issue while reviewing your suggestion, so it would be great if you could roll in a fix for it as well. This line in between the two sudoku pictures, quoted below, references setting the pixel to 64 and since they are now all between 0 and 1, I think it must be a remnant from when it was a different format.

"Your task is to turn all of the white pixels in the image to a light gray colour, say with the intensity of each formerly white pixel set to 64. The results should look like this:"

Thanks again and looking forward to your pull request.

quist00 avatar Oct 13 '22 23:10 quist00

Awesome. I made a first attempt at the callout box in pr #235 and also fixed the other issue, you mention.

iimog avatar Oct 21 '22 09:10 iimog