在使用pydensecrf进行densecrf时出现ValueError
def dense_crf(img, probs, n_labels=2):
h = probs.shape[0]
w = probs.shape[1]
probs = np.expand_dims(probs, 0)
probs = np.append(1 - probs, probs, axis=0)
d = dcrf.DenseCRF2D(w, h, n_labels)
U = -np.log(probs)
U = U.reshape((n_labels, -1))
U = np.ascontiguousarray(U)
img = np.ascontiguousarray(img)
U = U.astype(np.float32)
d.setUnaryEnergy(U) # Unary
d.addPairwiseGaussian(sxy=20, compat=3) #
d.addPairwiseBilateral(sxy=30, srgb=20, rgbim=img, compat=10)
Q = d.inference(5)
Q = np.argmax(np.array(Q), axis=0).reshape((h, w))
return Q
image = np.random.randint(0, 255, (256, 256, 3))
mask = np.random.rand(256, 256)
mask = dense_crf(image, mask)
Traceback (most recent call last):
File "G:/python/denseCRF/crf.py", line 34, in <module>
mask = dense_crf(image, mask)
File "G:/python/denseCRF/crf.py", line 24, in dense_crf
d.addPairwiseBilateral(sxy=30, srgb=20, rgbim=img, compat=10)
File "densecrf.pyx", line 126, in pydensecrf.densecrf.DenseCRF2D.addPairwiseBilateral
ValueError: Buffer dtype mismatch, expected 'unsigned char' but got 'long'
错误原因:输入图像的类型与addPairwiseBilateral()方法要求不符
解决方法:将image转换为np.uint8类型
mask = dense_crf(image.astype(np.uint8), mask)