使用Python OpenCV缩放图像时触发cv::OutOfMemoryError内存分配失败
解决OpenCV cv2.resize内存不足错误(图像缩放场景)
错误原因
你在调用cv2.resize时误用了fx和fy参数:这两个参数的作用是缩放因子(比如0.5代表缩小至原尺寸的50%),但你却传入了scale*width和scale*height计算出的像素值,导致程序试图生成一个尺寸夸张的超大图像(以你的案例为例,原宽5456,fx传入2728,相当于把宽度放大2728倍,所需内存直接突破系统上限),最终触发内存分配失败的错误。
修正后的代码
你可以选择两种正确的实现方式:
方式1:使用fx/fy传入缩放因子
import cv2 import numpy as np import time src = input("enter the local path of the image the you want to resize: ") img_old = cv2.imread(rf"{src}", cv2.IMREAD_UNCHANGED) height, width, no_of_channels = img_old.shape print("The size of the original image is : ", height, "x", width, "(height x width)") time.sleep(1) scale = int(input("Enter how much percentage that you want to resize your image, example-50 (decreases by 50%), 200(increases by 200%) : ")) scale = scale / 100 # 直接传入缩放因子fx和fy,无需计算像素值 scaled_image = cv2.resize(img_old, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) cv2.imwrite('newimage.png', scaled_image) cv2.waitKey(0)
方式2:使用dsize指定目标尺寸
如果你想明确指定目标像素尺寸,可以用dsize参数,此时不需要传fx/fy:
import cv2 import numpy as np import time src = input("enter the local path of the image the you want to resize: ") img_old = cv2.imread(rf"{src}", cv2.IMREAD_UNCHANGED) height, width, no_of_channels = img_old.shape print("The size of the original image is : ", height, "x", width, "(height x width)") time.sleep(1) scale = int(input("Enter how much percentage that you want to resize your image, example-50 (decreases by 50%), 200(increases by 200%) : ")) scale = scale / 100 # 计算目标尺寸,传入dsize参数 target_width = int(width * scale) target_height = int(height * scale) scaled_image = cv2.resize(img_old, (target_width, target_height), interpolation=cv2.INTER_LINEAR) cv2.imwrite('newimage.png', scaled_image) cv2.waitKey(0)
关键说明
cv2.resize的参数规则:要么指定dsize(目标尺寸,格式为(宽, 高)),要么指定fx和fy(宽、高方向的缩放因子),两种方式二选一即可,不要混合误用。- 原代码还存在逻辑对应错误:
fx对应宽度方向的缩放因子,fy对应高度方向,原代码里把宽度的像素值传给fx,高度的像素值传给fy,进一步放大了错误影响。
内容的提问来源于stack exchange,提问作者Sai Dheeraj
相关产品推荐
相关产品推荐

