报错 cv2.error: OpenCV(4.5.4) :-1: error: (-5:Bad argument) in function 'inRange' > Overload resolution failed: > - src is not a numpy array, neither a scalar > - Expected Ptr<cv::UMat> for argument 'src'
时间: 2023-08-28 15:37:15 浏览: 465
根据错误提示,`inRange` 函数期望的参数类型是 `numpy` 数组或 `UMat` 类型。你可以将 `jietushuju` 对象转换为 `numpy` 数组类型,然后再传递给 `remove_colors_except` 函数。修改代码如下:
```python
import numpy as np
import cv2
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
class fangfa:
def jietu(self, hwnd):
img = screen.grabWindow(hwnd).toImage()
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer,"bmp")
dd = Image.open(buffer)
#dd.save("1.bmp")
return dd
def remove_colors_except(self, image, target_colors, threshold):
image = np.array(image)
result = np.zeros_like(image)
for target_color in target_colors:
#例如 target_colors = ['FF0000', '00FF00', '0000FF']
# 将目标色格式 "FFFFFF" 转换成 RGB 值
blue = int(target_color[0:2], 16)
green = int(target_color[2:4], 16)
red = int(target_color[4:6], 16)
# 计算目标颜色的范围
lower_range = np.array([blue - threshold, green - threshold, red - threshold])
upper_range = np.array([blue + threshold, green + threshold, red + threshold])
# 创建掩码,将目标颜色范围以外的像素设为黑色,目标颜色范围内的像素设为白色
mask = cv2.inRange(image, lower_range, upper_range)
# 将目标颜色范围内的像素设为白色
result[mask > 0] = (255, 255, 255)
# 显示结果图像
cv2.imwrite('222.bmp', result)
return result
ff = fangfa()
def main():
hwnd = ff.huoqujubin('【魔域】')
if hwnd != []:
jietushuju = ff.jietu(hwnd)
ff.remove_colors_except(jietushuju, ['FFFFFF'], 0)
```
在修改后的代码中,我们首先将 `jietushuju` 对象转换为 `numpy` 数组类型,然后再传递给 `remove_colors_except` 函数。这样就能够避免出现 `inRange` 函数参数类型错误的问题。
阅读全文