thresh.cpp:1676: 错误: (-215:断言失败) src.type() == CV_8UC1 在函数“cv::adaptiveThreshold”中

Jeb*_*b50 2 python opencv

在 OpenCV 的Adaptive -Thresholding学习本教程,复制精确代码

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('sudoku.jpg',0)
img = cv.medianBlur(img,5)
ret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
            cv.THRESH_BINARY,11,2)
th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()
Run Code Online (Sandbox Code Playgroud)

OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-m8us58q4\opencv\modules\imgproc\src\thresh.cpp:1676:错误:(-215:断言失败)函数 'cv::adaptiveThreshold' 中的 src.type() == CV_8UC1
文件“C:\Users\me\Documents\test\AdaptiveThresholding.py”,第 8 行,在 th2 = cv.adaptiveThreshold(img,255,cv. ADAPTIVE_THRESH_MEAN_C,\

opencv-python 4.5.2.52

Python 3.9.5

在此输入图像描述

Tim*_*rts 9

这不是确切的代码。确切的代码读取灰度 PNG。你有一个彩色 JPG。这就是区别。自适应阈值需要灰度图像。所以,添加:

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Run Code Online (Sandbox Code Playgroud)