You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV threshold函数(-215)报错:src.type()不匹配问题求助

Fixing OpenCV Threshold Error (-215: src.type() Mismatch)

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 (np for numpy, plt for pyplot, pd for pandas)—this makes your code easier to read for other developers.
  • If your img comes 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:50:10