无法使用 imread() 加载图像

Unable to load image using imread()

我不确定为什么会这样,但我无法使用 imread() 加载图像。我可以在 Paint 中打开该图像,并在保存该图像后加载并显示该图像。我正在使用 Jupyter 笔记本。

import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

def displayImage(image):
 plt.imshow(image)
 plt.show()

image = cv2.imread('path/to/image')
displayImage(image)

输出

预期输出:

并检查实际加载的数据。使用 image.shape() 检查大小,查看 max/min/mean 值或者如果您使用 spyder(强烈推荐),查看变量查看器中的数据。

ps。对于单个显示项目,不需要 plt.show() 命令

加载图像后使用:

image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

问题是您的图像不包含任何非零红色、绿色或蓝色像素,它完全是黑色的。它看起来如何用 "@ @ 6 L" 显示的唯一原因是因为它有一个 alpha/transparency 通道,可以掩盖黑色并显示白色 PNG 背景颜色。

如果您使用 ImageMagick 的 identify 查看它,您将看到:

identify -verbose a.png | more
Image: a.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: DirectClass
  Geometry: 203x50+0+0
  Resolution: 37.79x37.79
  Print size: 5.37179x1.3231
  Units: PixelsPerCentimeter
  Colorspace: sRGB
  Type: Bilevel
  Base type: Undefined
  Endianess: Undefined
  Depth: 8-bit
  Channel depth:
    Red: 1-bit
    Green: 1-bit
    Blue: 1-bit
    Alpha: 8-bit
  Channel statistics:
    Pixels: 10150
    Red:
      min: 0  (0)
      max: 0 (0)                 <--- Brightest Red is zero
      mean: 0 (0)
      standard deviation: 0 (0)
      kurtosis: -3
      skewness: 0
      entropy: 0
    Green:
      min: 0  (0)
      max: 0 (0)                 <--- Brightest Green is zero
      mean: 0 (0)
      standard deviation: 0 (0)
      kurtosis: -3
      skewness: 0
      entropy: 0
    Blue:
      min: 0  (0)
      max: 0 (0)                  <--- Brightest Blue is zero
      mean: 0 (0)
      standard deviation: 0 (0)
      kurtosis: -3
      skewness: 0
      entropy: 0
    Alpha:
      min: 0  (0)
      max: 255 (1)                         <--- Alpha channel is only one with info
      mean: 16.477 (0.0646159)
      standard deviation: 58.73 (0.230314)
      kurtosis: 10.7342
      skewness: 3.50997
      entropy: 0.128008
   ...
   ...
   Background color: white       <--- Background is white
   ...
   ...

答案是用 cv2.IMREAD_UNCHANGED 读取所有四个通道,并且只使用第 4 个/alpha 通道:

def read_transparent_png(filename):
image_4channel = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
alpha_channel = image_4channel[:,:,3]
rgb_channels = image_4channel[:,:,:3]

here.

中提取的代码

发生这种情况是因为您的图像处于 RGBA 模式(您的背景是透明的)。 所以你需要在 RGBA 模式下阅读你的图像:

image = cv2.imread('path/to/image.png',-1)

或:

from scipy.ndimage import imread
rgba = imread('path/to/image.png', mode='RGBA')

结果: