OpenCV threshold函数(-215)报错:src.type()不匹配问题求助
Hey there! Let’s break down this error and get your code working again, step by step.
What the Error Actually Means
That scary-looking OpenCV error is just an assertion failure—it’s telling you the image you’re feeding to cv2.threshold() doesn’t meet the function’s requirements. Translating the jargon:
OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1406: error: (-215) src.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3)) in function cv::threshold
This simply means: "The input image isn’t an 8-bit single-channel grayscale image"—the only format cv2.threshold() accepts for this binary + Otsu operation. Your blur image (derived from img) is almost certainly a 3-channel color image, or a non-8-bit format like float.
How to Fix It
You just need to ensure your input image is converted to grayscale before running the thresholding. Here’s the corrected version of your code, with key fixes and standard Python conventions:
import numpy as np from matplotlib import pyplot as plt import pandas as pd import math from sklearn import preprocessing from sklearn import svm import cv2 # Step 1: Get your image into grayscale format # Option 1: Load directly as grayscale (replace with your image path) img = cv2.imread("your_image_file.jpg", 0) # The '0' flag forces grayscale loading # Option 2: If you already have a color image, convert it # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Step 2: Run your existing processing pipeline blur = cv2.GaussianBlur(img, (5, 5), 0) ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) image = np.invert(th3) plt.imshow(image, 'gray') plt.show()
Quick Extra Tips
- I adjusted your import aliases to match common Python norms (
npfor numpy,pltfor pyplot,pdfor pandas)—this makes your code easier to read for other developers. - If your
imgcomes from a source that outputs float values (like some ML preprocessing steps), convert it to 8-bit first before processing:img = img.astype(np.uint8)
内容的提问来源于stack exchange,提问作者SidAvenger

