coding: utf-8 import cv2 import numpy as np import cv2 as cv import os def motion_blur1(image, degree=10, angle=45): image = np.array(image) # 这里生成任意角度的运动模糊kernel的矩阵, degree越大,模糊程度越高 M = cv.getRotationMatrix2D((degree / 2, degree / 2), angle, 1) motion_blur_kernel = np.diag(np.ones(degree)) motion_blur_kernel = cv.warpAffine(motion_blur_kernel, M, (degree, degree)) motion_blur_kernel = motion_blur_kernel / degree blurred = cv.filter2D(image, -1, motion_blur_kernel) # convert to uint8 cv.normalize(blurred, blurred, 0, 255, cv.NORM_MINMAX) blurred = np.array(blurred, dtype=np.uint8) return blurred filePath = r'D:\Users\Administrator\PycharmProjects\pythonProject\paper_need\blur' for i in os.listdir(filePath): outPath = r'D:\Users\Administrator\PycharmProjects\pythonProject\paper_need\blur.' + str(i) img = cv.imread("./deblur/"+i) img = cv.UMat(img) # 将numpy数组转换为UMat类型 img_ = motion_blur1(img) cv.imwrite(outPath,img_),上述代码出现问题:cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'filter2D' > Overload resolution failed: > - src data type = 17 is not supported > - Expected Ptrcv::UMat for argument 'src'
时间: 2024-03-21 15:39:23 浏览: 96
这个错误是由于filter2D函数的输入类型不匹配导致的。在这里,您正在使用UMat类型的图像,但是filter2D函数不支持UMat类型的图像。您可以尝试将UMat类型的图像转换为numpy数组类型的图像,然后再进行模糊处理。这里是修改后的代码:
```python
import cv2
import numpy as np
import os
def motion_blur1(image, degree=10, angle=45):
image = np.array(image)
# 生成任意角度的运动模糊kernel的矩阵, degree越大,模糊程度越高
M = cv2.getRotationMatrix2D((degree / 2, degree / 2), angle, 1)
motion_blur_kernel = np.diag(np.ones(degree))
motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))
motion_blur_kernel = motion_blur_kernel / degree
# 将UMat类型的图像转换为numpy数组类型的图像
blurred = cv2.filter2D(image.get(), -1, motion_blur_kernel)
# convert to uint8
cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
blurred = np.array(blurred, dtype=np.uint8)
# 将numpy数组类型的图像转换为UMat类型的图像
blurred = cv2.UMat(blurred)
return blurred
filePath = r'D:\Users\Administrator\PycharmProjects\pythonProject\paper_need\blur'
for i in os.listdir(filePath):
outPath = r'D:\Users\Administrator\PycharmProjects\pythonProject\paper_need\blur.' + str(i)
img = cv2.imread("./deblur/"+i)
img = cv2.UMat(img)
img_ = motion_blur1(img)
cv2.imwrite(outPath,img_.get())
```
这里将UMat类型的图像转换为numpy数组类型的图像,然后进行模糊处理,最后再将numpy数组类型的图像转换为UMat类型的图像。这样就可以解决这个问题了。
阅读全文