예제 #1
0
def test(epoch):
    global best_acc
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    with torch.no_grad():
        for batch_idx, (inputs, targets) in enumerate(testloader):
            inputs, targets = inputs.to(device), targets.to(device)
            outputs = net(inputs)
            loss = criterion(outputs, targets)
            
            test_loss += loss.item()
            _, predicted = outputs.max(1)
            total += targets.size(0)
            correct += predicted.eq(targets).sum().item()
            
            print('Loss: %.3f | Acc: %.3f%% (%d/%d)' %(test_loss/(batch_idx+1), 100.*correct/total, correct, total))
    acc = 100.*correct/total
    if acc > best_acc:
        print("Saving")
        state = {'net':net.state_dict(), 'acc':acc, 'epoch':epoch,}
        if not os.path.isdir('checkpoint'):
            os.mkidr('checkpoint')
        torch.save(state, './checkpoint/ckpt.pth')
        best_acc = acc
예제 #2
0
global W, G, R
if sys.platform in ['linux', 'linux2']:
    W = '\033[0m'
    G = '\033[1;92m'
    R = '\033[1;91m'
else:
    W = ''
    G = ''
    R = ''

try:
    os.mkdir('result')
except:
    pass
try:
    os.mkidr('result/dump')
except:
    pass
try:
    os.mkdir('result/dump/phone')
except:
    pass


class Dump:
    def __init__(self):
        self.token = open('log/token').read()
        self.HD = {'User-Agent': open('UserAgent/ua.txt').read()}
        self.id = []
        self.Main()
예제 #3
0
		昨天:datetime.date.today() - datetime.timedelta(days=-1)
		明天:datetime.date.today() - datetime.timedelta(days=1)
	








import os
	获取当前路径: os.getcwd()
	修改当前路径:os.chdir(path)
	获取指定路径下的文件名:os.listdir(path)
	创建文件夹:os.mkidr(dirname)
	创建递归文件夹:os.makedirs()
	删除目录:os.rmdir()
	递归删除空目录:os.removedirs()
	执行系统命令:os.system('ls')
	获取文件或文件夹信息:os.stat()
	重命名文件或文件夹:os.rename()

	获取系统环境变量:os.getenv()
	修改或添加环境变量:os.putenv()

	获取路径间隔符:print(os.sep)		#win:  \  , linux:  /
	获取操作系统换行符:print(repr(os.linesep))   #win:  \r\n  ,linux: \n

	获取文件名及其所在路径:os.path.split(path)  ——>  list[dirname,filename]
	合并路径和文件名:os.path.join(dirname,filename)  ——>  str:path
def create_masks(patch_min_width,
                 patch_min_height,
                 WSI_path,
                 xml_file_path,
                 save=False,
                 separate_objects=False,
                 target_path=None,
                 magnification=20):
    # Creats masks for one ROI
    # returns dictionary, with mask name and mask
    iterations_x_direction, iterations_y_direction = calc_number_of_iterations_for_sliding_window(
        patch_min_width, patch_min_height, WSI_path, xml_file_path,
        magnification)

    adapted_patch_width, adapted_patch_height = adapt_sliding_window_size_for_ROI(
        patch_min_width, patch_min_height, WSI_path, xml_file_path)

    mask_dict = {}

    head, tail = ntpath.split(xml_file_path)
    xml_file_name = tail
    pattern = re.compile('(.xml)')
    patient_ID = pattern.sub('', xml_file_name)

    start_y = int(-adapted_patch_height)
    end_y = 0
    ROI_mask = create_mask_for_ROI(WSI_path, xml_file_path, magnification)
    number = 0

    if save == True and separate_objects == False:
        gt_path = target_path + "/gt"
    if save == True and separate_objects == False and not os.path.exists(
            gt_path):
        os.mkdir(target_path + "/gt")

    for row in range(math.floor(iterations_y_direction)):

        # next step
        start_y += int(adapted_patch_height)
        end_y += int(adapted_patch_height)

        start_x = int(-adapted_patch_width)
        end_x = 0

        for col in range(math.floor(iterations_x_direction)):
            number += 1
            start_x += int(adapted_patch_width)
            end_x += int(adapted_patch_width)

            mask = ROI_mask[start_y:end_y, start_x:end_x, :]

            mask_name = patient_ID + "_mask_" + str(number)
            mask_dict[mask_name] = mask

            if save == True and separate_objects == False:
                mask = np.zeros((mask[:, :, :3].shape), dtype=np.uint8)
                mask[:, :,
                     2] = 1  # set everything to background in blue channel
                mask[:, :,
                     2][mask[:, :,
                             1] != 0] = 2  # set glands to 2 in blue channe
                mask = Image.fromarray(mask)
                new_file_path = os.path.join(target_path + "/gt/",
                                             mask_name + ".png")
                mask.save(new_file_path)

            #TODO: if option is set to save==False and separate_objet == True
            #      the mask of each separated object should be saved in a dictionary
            if save == True and separate_objects == True:

                new_folder_path = target_path + '/' + patient_ID + "_image_" + str(
                    number)
                if not os.path.exists(new_folder_path):
                    os.mkidr(new_folder_path)

                os.mkdir(new_folder_path + '/mask')
                object = '_object_'
                gray_mask = rgb2gray(np.array(mask))

                ret, bw_mask = cv2.threshold(gray_mask, 0, 255,
                                             cv2.THRESH_BINARY)
                labels, num = label(bw_mask, return_num=True)

                for L in range(1, num + 1):
                    plt.imsave(
                        new_folder_path + '/mask/' + mask_name + object +
                        str(L) + '.png', np.uint8(labels == L))


#######################################################
    return mask_dict