SoFunction
Updated on 2024-11-15

python using matplotlib to display image distortion solution

When displaying images in python, we will encounter the problem of image color distortion when using the matplotlib module.

The image to be displayed is:

在这里插入图片描述

import cv2
from matplotlib import pyplot as plt
img = ('demo_2.jpg',0)
(img, cmap = 'gray', interpolation = 'bicubic')
([]), ([]) # to hide tick values on X and Y axis
()

The simple code above runs as:

在这里插入图片描述

We found that the image is displayed, but with the original image in the color gap is still quite large, originally a fat white boy was displayed in the yin and yang, which is certainly not good. So how do we make this fat white boy with matplotlib module to display it perfectly.

See the code:

import cv2
from matplotlib import pyplot as plt
img = ('demo_2.jpg', cv2.IMREAD_ANYCOLOR)
b,g,r = (img)
img2 = ([r, g, b])
(121)
(img, cmap = 'gray', interpolation = 'bicubic')
([])
([])
(122)
(img2, cmap = 'gray', interpolation = 'bicubic')
([])
([])
()

The above code runs as follows:

在这里插入图片描述

We can find through the code, as long as the channel in accordance with the order of the bgr combination, the picture can be displayed without distortion, so we understand the reasons for the distortion of the above picture and the solution to the distortion.

Addendum: python plot image distortion (to avoid type font 3 fonts)

When using python to draw a picture, I started to use png to save it directly, but I didn't realize that type font 3 would be used in the picture by default, which resulted in the picture not being clear once it was zoomed in after putting it into the latex compiler.

So searched a lot for a solution to modify the image settings

That is, insert the following three lines:

# Switch to Type 1 Fonts. 
[''] = True
['pdf.use14corefonts'] = True
[''] = True

But my problem is still not solved...

The above setup is needed, it's just that my output image is saved as a png that causes it. So, in the end, I replaced the drawing operation separately as well as added some packages, i.e., the

import matplotlib
('PDF')
import  as plt
from .backend_pdf import PdfPages
('', bbox_inches='tight') 

Picture to pdf output, the final output of the picture will not have type 3 font problem, that is, no matter how big the picture, can be very clear!

Therefore, PDF is preferred for saving experimental results using python.

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more. If there is any mistake or something that has not been fully considered, please do not hesitate to give me advice.