报错 cv2.imwrite(r'./pgd_img/adver_results/{}.jpg'.format(i), np.transpose(adv_imgs), (1, 2, 0)) cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:738: error: (-2:Unspecified error) in function 'bool __cdecl cv::imwrite_(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &,const class std::vector<class cv::Mat,class std::allocator<class cv::Mat> > &,const class std::vector<int,class std::allocator<int> > &,bool)' > Encoding 'params' must be key-value pairs: > '(params.size() & 1) == 0' > where > 'params.size()' is 3
时间: 2023-12-19 17:04:05 浏览: 29
这个报错提示参数设置有误,具体来说是imwrite函数的第三个参数不符合要求。根据报错信息,看起来是传递的参数列表长度不符合要求,需要使用key-value pairs来设置参数。建议检查一下传递给imwrite函数的第三个参数是否正确,应该使用一个字典来设置参数,其中包含图像的编码方式、压缩质量等参数。例如可以这样设置:
```
cv2.imwrite(r'./pgd_img/adver_results/{}.jpg'.format(i), np.transpose(adv_imgs, (1, 2, 0)), params={"quality": 100})
```
其中,quality表示JPEG图像的压缩质量,取值范围是0-100,100表示无损压缩。经过上述修改后,应该就可以成功保存图像了。
相关问题
cv2.imwrite(path + '/'+'{}.jpg'.format(i), face_array)
这段代码使用 OpenCV 库中的 `imwrite` 函数将 `face_array` 保存为 JPEG 格式的图像文件,文件名为 `{i}.jpg`,保存路径为 `path`。其中,`i` 是一个整数变量,用于为不同的图像文件编号。如果 `path` 是一个相对路径,则文件将被保存在当前工作目录下的相应子目录中。
cv2.imwrite('path/to/folder/image.jpg', img)中的img格式是tensor还是numpy
`cv2.imwrite()` 函数需要的参数是一个 numpy 数组,因此在将图像保存为文件时,需要先将 PyTorch 的 tensor 转换成 numpy 数组。可以使用 `numpy()` 函数将 tensor 转换成 numpy 数组。
示例代码如下:
```python
import cv2
import torch
# 从文件中读取图像,返回的是 numpy 数组
img = cv2.imread('path/to/image.jpg')
# 将 numpy 数组转换成 tensor
tensor_img = torch.from_numpy(img)
# 对 tensor_img 进行操作,修改像素值
# 将 tensor_img 转换回 numpy 数组
numpy_img = tensor_img.numpy()
# 将 numpy 数组保存为文件
cv2.imwrite('path/to/folder/image.jpg', numpy_img)
```
在这段代码中,我们首先使用 OpenCV 的 `imread()` 函数读取图像,返回的是 numpy 数组。然后,我们将 numpy 数组转换成 PyTorch 的 tensor,对 tensor 进行操作,然后再将其转换回 numpy 数组。最后,我们将 numpy 数组使用 `imwrite()` 函数保存为文件。需要注意的是,此时的 `numpy_img` 是一个 numpy 数组,可以直接传入 `imwrite()` 函数中。