使用python-opencv读取超大jpg图片时报错:
Traceback (most recent call last):
File "E:/pythonWorkspace/python-demo/hbase_test.py", line 22, in <module>
mat = cv2.imread(r"E:\work\tmp\Big_Image.jpg")
cv2.error: OpenCV(4.1.2) D:\Build\OpenCV\opencv-4.1.2\modules\imgcodecs\src\loadsave.cpp:75: error: (-215:Assertion failed) pixels <= CV_IO_MAX_IMAGE_PIXELS in function 'cv::validateInputImageSize'
这是由于opencv支持读取的图片最大宽度为220像素,最大高度为220像素,最大面积为230像素。
我们要读取一张18亿像素,接近400M的图片该如何呢?
在运行环境的环境变量中添加配置:OPENCV_IO_MAX_IMAGE_PIXELS=20000000000,增大opencv的最大像素读取值,然后再通过opencv读取图片就能正常读取了。
在idea或者pycharm中可以这样配置
在linux中可以将该配置添加到/etc/profile中
但是在程序中设置环境变量没有成功
import cv2
import os
# 这三个方法都不行
# os.putenv('OPENCV_IO_MAX_IMAGE_PIXELS','2000000000')
#os.environ['OPENCV_IO_MAX_IMAGE_PIXELS']='2000000000'
os.environ.setdefault('OPENCV_IO_MAX_IMAGE_PIXELS', '2000000000')
print(os.environ['OPENCV_IO_MAX_IMAGE_PIXELS'])
mat = cv2.imread(r"E:\Big_Image.jpg")
print(mat.shape)
使用PIL的Image读取大图,也要提前设置最大像素:Image.MAX_IMAGE_PIXELS = None
from PIL import Image
import numpy as np
Image.MAX_IMAGE_PIXELS = None
mat = Image.open(r"E:\Big_Image.jpg")
img = np.array(mat)
print(img.shape)
另外,skimage的io也可以结合PIL的Image模块读取大图
from PIL import Image
from skimage import io
Image.MAX_IMAGE_PIXELS = None
mat = io.imread(r"E:\Big_Image.jpg")
print(mat.shape)