OpenCV (BGR mode) and Matplotlib (RGB mode)

OpenCV (BGR mode) and Matplotlib (RGB mode)

Color image loaded by OpenCV is in BGR mode. But Matplotlib displays in RGB mode. So color images will not be displayed correctly in Matplotlib if image is read with OpenCV. Please see the exercises for more details.
OpenCV 加载的彩色图像处于 BGR 模式。但 Matplotlib 以 RGB 模式显示。因此,如果使用 OpenCV 读取图像,则 Matplotlib 中的彩色图像将无法正确显示。有关详细信息,请参阅练习。

There is some problem when you try to load color image in OpenCV and display it in Matplotlib.
当您尝试在 OpenCV 中加载彩色图像并在 Matplotlib 中显示它时,会出现问题。

There is a slight difference in pixel ordering in OpenCV and Matplotlib. OpenCV follows BGR order, while matplotlib likely follows RGB order.
OpenCV 和 Matplotlib 中的像素排序略有不同。OpenCV 遵循 BGR 顺序,而 matplotlib 可能遵循 RGB 顺序。

So when you display an image loaded in OpenCV using pylab functions, you may need to convert it into RGB mode. Below method demonstrate it:
因此,当您使用 pylab 函数显示在 OpenCV 中加载的图像时,您可能需要将其转换为 RGB 模式。下面的方法演示了它:

1. Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import os
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
current_directory = os.path.dirname(os.path.abspath(__file__))

print(16 * "++--")
print("current_directory:", current_directory)
print(16 * "++--")

img_bgr = cv2.imread('/home/strong/sunergy_moonergy/object_counter/parking_system.jpg')
b, g, r = cv2.split(img_bgr)
img_rgb = cv2.merge([r, g, b])

plt.subplot(121)
plt.title("BGR image")
plt.imshow(img_bgr)  # distorted color

plt.subplot(122)
plt.title("RGB image")
plt.imshow(img_rgb)  # true color

plt.show()

cv2.imshow('BGR image', img_bgr)  # true color
cv2.imshow('RGB image', img_rgb)  # distorted color
cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

### 使用 OpenCV 实现绿色车牌识别 #### 图像预处理 为了有效检测并识别绿色车牌,图像预处理阶段至关重要。由于不同库对于色彩空间的理解存在差异,在读取和展示图片时可能会遇到色差问题。当利用 `opencv` 加载图像后,其默认采用 BGR 色彩模式;然而,`matplotlib.pyplot` (简称 `plt`) 则期望输入 RGB 彩色数据。因此,若要通过 `plt` 正确呈现由 `cv2.imread()` 获取到的画面,则需交换红色与蓝色分量位置[^1]。 ```python import numpy as np import cv2 from matplotlib import pyplot as plt def bgr_to_rgb(image_bgr): """Convert an image from BGR to RGB color space.""" return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) image_path = 'path/to/green_license_plate.jpg' img_bgr = cv2.imread(image_path) img_rgb = bgr_to_rgb(img_bgr) # Display the converted image using Matplotlib without color shift. plt.figure(figsize=(8, 6)) plt.axis('off') plt.imshow(img_rgb) plt.show() ``` #### HSV颜色空间转换 考虑到自然场景下的光照变化可能影响基于固定阈值的方法效果,可以考虑将原始彩色图像转化为HSV模型,并专注于其中的色调(Hue)部分来定位特定范围内的绿色区域。这里提到V通道可用于后续操作中的亮度调整或特征提取过程[^2]。 ```python def rgb_to_hsv(image_rgb): """Transforms an input image into its corresponding representation under HSV colorspace""" hsv_image = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2HSV) h_channel, s_channel, v_channel = cv2.split(hsv_image) # For visualization purposes only; not necessary for actual processing. fig, axes = plt.subplots(1, 3, figsize=(15, 5)) titles = ['Hue', 'Saturation', 'Value'] channels = [h_channel, s_channel, v_channel] for ax, channel, title in zip(axes.ravel(), channels, titles): ax.set_title(title) ax.imshow(channel, cmap='gray') ax.axis('off') plt.tight_layout() plt.show() rgb_to_hsv(img_rgb) ``` #### 定位绿色区域 针对中国标准下绿牌车辆的特点——即车牌底色呈翠绿色这一事实,可以通过设定合理的上下限区间筛选出符合条件的目标对象。具体来说就是选取适当的角度区间对应于HSI体系里的“青蓝至黄绿”。 ```python lower_green = np.array([70, 43, 46]) upper_green = np.array([90, 255, 255]) mask = cv2.inRange(hsv_image, lower_green, upper_green) result = cv2.bitwise_and(img_rgb, img_rgb, mask=mask) fig, axs = plt.subplots(1, 2, figsize=(12, 6)) axs[0].imshow(mask, cmap="gray") axs[0].set_title("Mask") axs[1].imshow(result) axs[1].set_title("Result after masking green areas.") for ax in axs.flat: ax.axis('off') plt.show() ``` #### 边缘检测与轮廓分析 完成上述步骤之后,下一步便是应用边缘算子(如Canny Edge Detector),进而获取二值化的边界信息。随后借助形态学运算消除噪声干扰项,最终依靠连通域标记技术找出最有可能属于车牌形状的那个矩形框体结构。 ```python edges = cv2.Canny(mask, threshold1=100, threshold2=200) kernel = np.ones((3, 3), dtype=np.uint8) dilated_edges = cv2.dilate(edges, kernel, iterations=1) contours, _ = cv2.findContours(dilated_edges.copy(), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)[-2:] rectangles = [] for contour in contours: x, y, w, h = cv2.boundingRect(contour) aspect_ratio = float(w)/h if 2 <= aspect_ratio <= 5 and area >= min_area_threshold: rectangles.append(((x,y),(w,h))) if len(rectangles)>0: best_rect = max(rectangles,key=lambda r:r[-1][0]) else: raise ValueError("No suitable license plate found.") (x_top_left, y_top_left), (width, height) = best_rect cropped_lp = result[y_top_left:y_top_left+height,x_top_left:x_top_left+width,:] plt.imshow(cropped_lp); plt.title('Detected License Plate'); plt.axis('off'); plt.show(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yongqiang Cheng

梦想不是浮躁,而是沉淀和积累。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值