如何在tensorflow(python)中调用opencv函数?

时间:2019-01-31 08:47:59

标签: tensorflow machine-learning deep-learning computer-vision

当我训练模型时,我已经自定义了损失函数。此函数中损失值的计算需要使用opencv函数。请参见代码,但是我弄错了。我不知道如何解决它,有人可以帮我吗?非常感谢。

#this is my loss function def instance_loss_function(predict,label): best_match_label_image=search_MaxPixelAccuracy_permutation(predict_convert_gray_image(predict),label) predict_image=predict loss_sum=0.0 best_match_label_image_contours_number=len(cv2.findContours( best_match_label_image.reshape(513,513), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]) predict_image_contours_number=len(cv2.findContours( predict_image.reshape(513,513), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]) counter_max=np.max([best_match_label_image_contours_number,predict_image_contours_number]) counter_min=np.min([best_match_label_image_contours_number,predict_image_contours_number]) for i in range(1,counter_min+1): ith_instance_IoU=compute_oneClassIoU(predict_image,best_match_label_image,i) if ith_instance_IoU!=0: loss_sum=loss_sum+2*(1/(1+ith_instance_IoU)-1/2) elif ith_instance_IoU==0: loss_sum=loss_sum+2 if np.abs(counter_max-counter_min)!=0: loss_sum=loss_sum+1*np.abs(counter_max-counter_min) return loss_sum 然后我这样调用损失函数:

loss=tf.py_func(instance_loss_function,[valid_logits,valid_labels],tf.float32)
train_op = optimizer.minimize(loss, global_step, var_list=train_var_list)

但是它不起作用, enter image description here

1 个答案:

答案 0 :(得分:0)

要能够训练您的网络张量流,需要创建一个可区分的操作图。如果要使用OpenCV函数,Tensorflow不知道如何为此构建导数。因此,您不能使用来自不同软件包的任意功能,不能将它们组合在一起并希望它能起作用。