Home > Backend Development > Python Tutorial > Why Do OpenCV-Loaded Images Display Inaccurate Colors in Matplotlib?

Why Do OpenCV-Loaded Images Display Inaccurate Colors in Matplotlib?

Mary-Kate Olsen
Release: 2024-10-24 18:44:49
Original
764 people have browsed it

Why Do OpenCV-Loaded Images Display Inaccurate Colors in Matplotlib?

OpenCV Color Discrepancy: Resolving Disparity between Loaded and Plotted Images

When utilizing OpenCV to load color images and display them using Matplotlib, it's not uncommon to encounter discrepancies in the displayed colors. This is due to the difference in default color orders between OpenCV and Matplotlib.

OpenCV stores images in the Blue-Green-Red (BGR) format, while Matplotlib expects images in the Red-Green-Blue (RGB) format. When displaying an image loaded with OpenCV in Matplotlib, the color channels are reversed, resulting in incorrect colors.

Solution: Converting BGR to RGB

To rectify this issue, we need to explicitly convert the loaded image from BGR to RGB using OpenCV's cvtColor function.

<code class="python">RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)</code>
Copy after login

By using RGB_img in the Matplotlib plot instead of the original img, we ensure that the color order matches the expectation of Matplotlib, and the colors are displayed correctly.

Updated Code

<code class="python">import cv2
import matplotlib.pyplot as plt

# Load image with BGR order (default for OpenCV)
img = cv2.imread('lena_caption.png', cv2.IMREAD_COLOR)

# Convert BGR to RGB for compatibility with Matplotlib
RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Create grayscale image
bw_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Create figure for plotting
fig, axes = plt.subplots(1, 2)

# Plot original image with corrected color order
axes[0].imshow(RGB_img)
axes[0].set_title('Original Image (RGB)')
axes[0].set_xticks([]); axes[0].set_yticks([])

# Plot grayscale image
axes[1].imshow(bw_img, cmap='gray')
axes[1].set_title('BW Image')
axes[1].set_xticks([]); axes[1].set_yticks([])

plt.show()</code>
Copy after login

The above is the detailed content of Why Do OpenCV-Loaded Images Display Inaccurate Colors in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template