error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imwrite' > Overload resolution failed: > - img is not a numerical tuple > - Expected Ptr<cv::UMat> for argument 'img'
时间: 2023-08-28 14:40:08 浏览: 58
这个错误通常是因为传递给cv2.imwrite()函数的图像数据格式不正确导致的。请确保您传递的图像数据是正确的,并且是一个有效的NumPy数组。
以下是一个示例代码,用于读取图像、缩放图像并保存到文件中:
```python
import cv2
# 读取图像
image = cv2.imread("example.png")
# 缩放图像
resized_image = cv2.resize(image, (0, 0), fx=0.5, fy=0.5)
# 保存图像
success = cv2.imwrite("resized_image.png", resized_image)
if success:
print("Image saved successfully")
else:
print("Error saving image")
```
在这个示例中,我们首先使用cv2.imread()函数读取名为 "example.png" 的图像。然后,我们使用cv2.resize()函数缩小图像的大小。最后,我们使用cv2.imwrite()函数将缩小后的图像保存到名为 "resized_image.png" 的文件中。注意,我们使用了success变量来检查cv2.imwrite()函数是否成功保存了图像。
相关问题
error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imencode' > Overload resolution failed: > - img is not a numpy array, neither a scalar > - Expected Ptr<cv::UMat> for argument 'img'
这个错误通常是因为`img`不是numpy数组或者cv::UMat指针类型导致的。可以检查一下`img`的类型,确保它是numpy数组,并且在调用`cv2.imencode()`函数时,将numpy数组传递给`img`参数。
如果`img`确实是numpy数组,那么可以将其转换为cv::UMat类型,然后再传递给`cv2.imencode()`函数。可以使用`cv2.UMat()`函数将numpy数组转换为cv::UMat类型,如下所示:
```
import cv2
import os
# 读取灰度图像
img_path = 'gray_image.jpg'
img = cv2.imread(img_path, 0)
# 将numpy数组转换为cv::UMat类型
img_um = cv2.UMat(img)
# 设置JPEG压缩参数
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
# 进行JPEG压缩
with open(img_path, 'rb') as f:
img_data = f.read()
result, compress_img = cv2.imencode('.jpg', img_um, encode_param)
# 计算压缩率
original_size = os.path.getsize(img_path)
compress_size = compress_img.size
compression_ratio = original_size / compress_size
# 解码压缩图像
decompress_img = cv2.imdecode(compress_img, 0)
# 显示压缩前后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Compressed Image', decompress_img)
print('Compression Ratio:', compression_ratio)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这样可以将numpy数组转换为cv::UMat类型,避免传递错误的参数类型。
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imencode'
This error occurs when there is a problem with the arguments passed to the 'imencode' function in OpenCV. This function is used to encode an image to a specific format, such as JPEG or PNG.
Possible reasons for this error include:
- The input image is not in a valid format or is corrupted.
- The encoding format specified is not supported by OpenCV.
- The parameters passed to the 'imencode' function are incorrect or incomplete.
To fix this error, check the input image and make sure it is in a valid format. Also, check the encoding format specified in the function and make sure it is supported by OpenCV. Finally, check the parameters passed to the 'imencode' function and ensure they are correct and complete.