首页 > 解决方案 > 如何在 Google Colab/Python 中将上传的 JPEG 图像转换为 unit8 类型?

问题描述

我正在尝试使用skimage.util将上传的图像(JPEG,gif)转换为Google Colab上的 uint8/16 类型。

# How to Import an image
from google.colab import files
from IPython.display import Image

# Convert to 8-bit uint
from skimage.util import img_as_uint

uploaded = files.upload()

img_as_uint(uploaded)

我在最后一行收到错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-c19636843da4> in <module>()
----> 1 img_as_uint(uploaded)

1 frames
/usr/local/lib/python3.6/dist-packages/skimage/util/dtype.py in convert(image, dtype, force_copy, uniform)
    248     if not (dtype_in in _supported_types and dtype_out in _supported_types):
    249         raise ValueError("Can not convert from {} to {}."
--> 250                          .format(dtypeobj_in, dtypeobj_out))
    251 
    252     if kind_in in 'ui':

ValueError: Can not convert from object to uint16.

标签: pythongoogle-colaboratoryscikit-image

解决方案


我找到了解决上述问题的简单方法。

我们可以使用 anmatplotlib.pyplot.imread('filename.jpg')将输入图像转换为图像对象/像素强度值。

代码如下:

# How to Import an image
from google.colab import files
import matplotlib.pyplot as plt

# Select file from Local Drive
uploaded = files.upload()

# Convert uploaded image into uint type
img = plt.imread('Lenna.jpg')

# Confirm pixel dtype, shape and range(should be 0-255)
print('Data Type:',img.dtype)
print('Data Shape:',img.shape)
print('Min: %.3f, Max: %.3f' % (img.min(), img.max()))

输出 :

Data Type: uint8
Data Shape: (373, 497, 3)
Min: 0.000, Max: 255.000

推荐阅读