问题:THRESH_OTSU mode: ‘src_type == CV_8UC1 || src_type == CV_16UC1’ where ‘src_type’ is 6(CV_64FC1)
def readTif(src):
dataset = gdal.Open(src)
if dataset ==None:
print(src+"文件无法打开")
im_width =dataset.RasterXSize
im_height = dataset.RasterYSize
im_bands = dataset.RasterCount
im_geotrans = dataset.GetGeoTransform()
im_pro = dataset.GetProjection()
im_data = dataset.ReadAsArray(0,0,im_width,im_height)
return im_data,im_width,im_height,im_bands,im_geotrans,im_pro
im_data,im_width,im_height,im_bands,im_geotrans,im_pro =readTif(path)
# img_ = cv2.imread(path,0) #灰度图输出
if im_bands > 3:
raise str("通道数过多无法转换")
elif im_bands == 3:
img = im_data[0,:,:] * 0.8 +im_data[1,:,:]*0.1 + im_data[2,:,:]*0.1
# SaveRaster(outPath, img, im_width, im_height, im_pro, im_geotrans, band=1)
blur = cv2.GaussianBlur(im_data, (5,5), 0) # 高斯滤波
ret1, th1 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) #方法选择为THRESH_OTSU

原因
从异常中发现,可能是数据的类型不一致导致的,分析算法原理

算法计算灰度级时,按照整数统计,且在0-255之间,但读取的数据为float类型,最终导致错误。
解决方案
img =img.astype("uint8")
ret1, th1 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) #方法选择为THRESH_OTSU
图像处理:解决浮点数据类型与阈值算法不匹配问题
博客讨论了在使用OpenCV进行图像处理时遇到的问题,即数据类型不匹配导致THRESH_OTSU阈值算法失败。原始代码尝试将浮点型数据转换为灰度图像并应用高斯滤波,然后进行二值化处理。问题在于,数据读取为CV_64FC1类型,而OTSU算法期望的是CV_8UC1或CV_16UC1类型的整数数据。解决方案是将图像数据转换为无符号8位整型。修复后的代码能够正确执行二值化操作。
2431

被折叠的 条评论
为什么被折叠?



