np.ndarray与PIL.Image对象相互转换时出现了 AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘

先介绍一下

用 cv2 的 imread()函数 和 PIL.Image 的 open()函数 这两个库中的函数分别读入两张图返回值的类型

上代码:

#!/usr/bin/env python
-*- coding: utf-8 -*-
@File  : 图片大小角度变换.py
@Author: 0moyi0
@Date  : 2021/10/31

import os
import cv2
import math
import numpy as np
from PIL import Image
import random

print(type(cv2.imread('img240.png', -1)))
print(type(Image.open('img240.png')))

图片

np.ndarray与PIL.Image对象相互转换时出现了 AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘

然后学习一下 np.ndarray 和 PIL.Image对象相互转换的实现

1、 实现PIL image到np.ndarray的转换

Image对象有crop功能,也就是图像切割功能,但是使用opencv读取图像的时候,图像需要转换为np.adarray类型,如

imshow() 函数里面的参数的是   numpy.ndarray  格式的

需要进行类型转换,所以使用下面的转换方式进行转换。

变换代码:

img = np.asarray(image)

需要注意的是,如果出现read-only错误,并不是转换的错误,一般是你读取的图片的时候,默认选择的是”r”,”rb”模式有关。

修正的办法: 手动修改图片的读取状态

img.flags.writeable = True  # 将数组改为读写模式

2、np.ndarray转换成PIL image

利用cv2.getRotationMatrix2D()函数或者cv2.warpAffine()对图像读取过后进行了一些角度、大小的旋转变换后,得到的是一个np.ndarray数组,这时候需要用到array转换成PIL  image进行对象间的变换。

变换代码:

Image.fromarray(np.uint8(img))

另外我今天变换的时候还碰到一个小错误

AttributeError: type object 'Image' has no attribute 'fromarray'

np.ndarray与PIL.Image对象相互转换时出现了 AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘

出现这个错误的时候需要注意

可能是导入的模块中有两个一样的
不同的两个module中可能存在相同的type,比如PIL和tkinter中都存在Image,这时候就要注意区分。

from PIL import Image,ImageTk
from tkinter import *
rgb_img=Image.fromarray(rgb_img)

解决办法

from PIL import ImageTk
from tkinter import *
import PIL.Image

np.ndarray与PIL.Image对象相互转换时出现了 AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘
import numpy as np
from PIL.Image import Image

解决方法

把那个 PIL.Image 改成 PIL 就可以了,一定要注意这上面是 PIL下面的 image库

import numpy as np
from PIL import Image

然后运行通过

当然还有一种方法可以直接通过 cv2.imwrite() 函数去直接将 array 保存成图片

    cv2.imwrite('AD_11.png', img, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

想了解上面这个函数或者更多相关的图像操作函数的话可以到下面的链接中去查看

cv2库中一些函数的使用_tp_0moyi0的博客-CSDN博客

Original: https://blog.csdn.net/tp_0moyi0/article/details/121065904
Author: tp_0moyi0
Title: np.ndarray与PIL.Image对象相互转换时出现了 AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/701270/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球