cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imshow'
时间: 2023-08-28 08:20:30 浏览: 302
这个错误可能是因为你给 `cv2.imshow()` 函数传递了错误的参数。请确保你传递给 `cv2.imshow()` 函数的第一个参数是窗口的名称,第二个参数是要显示的图像。例如:
```
import cv2
img = cv2.imread('image.jpg')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个例子中,我们首先使用 `cv2.imread()` 函数读取图像,然后将其传递给 `cv2.imshow()` 函数来显示图像。注意,第一个参数 `'image'` 是窗口的名称,第二个参数是要显示的图像 `img`。最后,我们使用 `cv2.waitKey()` 函数等待用户按下任意键,然后使用 `cv2.destroyAllWindows()` 函数关闭窗口。
相关问题
Traceback (most recent call last): File "D:\pythonProject\guidao.py", line 20, in <module> imggray = cv2.cvtColor(selected_files, cv2.COLOR_BGR2GRAY) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'cvtColor' > Overload resolution failed: > - src is not a numpy array, neither a scalar > - Expected Ptr<cv::UMat> for argument 'src'
根据错误信息看,是因为 `cvtColor` 函数的第一个参数需要是一个 numpy 数组,而 `selected_files` 是一个文件名列表,不是 numpy 数组。因此,你需要在读取每个文件时使用 OpenCV 的 `imread` 函数将其转换为 numpy 数组,然后再将其转换为灰度图像。
以下是修改后的代码:
```python
import os
import cv2
import random
# 文件夹路径
folder_path = "path/to/folder"
# 读取文件夹中所有文件名
files = os.listdir(folder_path)
# 随机选择 20 个文件
selected_files = random.sample(files, 20)
# 读取每个文件并转换为灰度图像
images = []
for file_name in selected_files:
file_path = os.path.join(folder_path, file_name)
img = cv2.imread(file_path)
imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
images.append(imggray)
# 显示灰度图像
for img in images:
cv2.imshow("Gray Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,我们使用 `imread` 函数读取每个文件,并使用 `cvtColor` 函数将其转换为灰度图像。然后将每个灰度图像添加到 `images` 列表中。最后,我们循环显示每个灰度图像。
请注意,你需要将 `folder_path` 替换为你的文件夹路径。
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类型,避免传递错误的参数类型。
阅读全文
相关推荐

















