# coding=utf-8
from os import listdir
from os.path import join
import numpy as np
from PIL import Image
# ÅжÏÊÇ·ñΪָ¶¨¸ñʽͼÏñ
def is_image_file(filename):
return any(filename.endswith(extension) for extension in ['.bmp', '.jpg', '.tif'])
def caltp(lab_path, seg_path):
'''tp'''
image_filenames = [x for x in listdir(lab_path) if is_image_file(x)]
recall_total = 0
with open('tp.csv', 'w') as f:
f.write('name,tp\n')
for imagename in image_filenames:
print(imagename)
seg_name = join(seg_path, imagename)
lab_name = join(lab_path, imagename)
seg = Image.open(seg_name)
lab = Image.open(lab_name)
seg1 = np.asarray(seg)
lab1 = np.asarray(lab)
seg2 = np.where(seg1 > 0, 1, 0)
lab2 = np.where(lab1 > 0, 1, 0)
tmp = seg2 + lab2
tp = np.sum(np.where(tmp == 2, 1, 0))
with open('tp.csv', 'a') as f:
f.write(imagename + ',' + tp.astype(np.str) + '\n')
print("****************************************")
return tp / len(image_filenames)
print(caltp(lab_path='C:\\Users\\Administrator\\Desktop\\1', seg_path='C:\\Users\\Administrator\\Desktop\\2'))
return tp / len(image_filenames)
缩进少了,你检查下,应该和for循环对齐
或者在for循环前面,加上tp=0
因为tp你现在是在for循环内定义的
这个程序修改后能在你的电脑上跑通吗?我的出现了如下问题,找不到解决方法。文件就在桌面,路径应该没问题啊。
global tp = np.sum(np.where(tmp == 2, 1, 0))
^
SyntaxError: invalid syntax
你看下错误的解释,tp还未定义就被使用了。其实你看函数的最后返回结果是tp,for循环和返回结果的tp都是一个层级,而for循环里面的tp是for循环的内层变量,所以在外面找的时候没有找到。
你可以尝试下,在for之前先定义下tp,如:
tp = 0
for :
tp = xxxx
return tp
如果tp的值还不对,就在for里面把tp加上global关键字。
你可以检查下Python版本,我的是3.6的没有这个问题。总之这是个命名空间的问题,自行理解哈。