You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:55:31