问题: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