首页 > 解决方案 > 如何在for循环中将代码更改为同步模式

问题描述

我正在做 Kaggle APTOS 比赛,我想根据以下步骤平衡图像数量:

  1. 使太暗的图像变亮
  2. 水平翻转,垂直翻转,两者都基于亮化的图像
  3. 根据 step2 图像更改对比度或锐度

但我发现预处理步骤是异步执行的,这意味着图像会同时变亮和翻转。

当我检查结果时,我发现翻转的图像仍然很暗。

我试过了print()time.sleep(1)但它们都不起作用。

以下是我的代码。谢谢你的建议!

#  get images per cat
# FIXME: synchronously in for loop
# brighten all, and then flip
# save records in df_new orderly
# TODO
# detect if the transformed image existe, if, then pass to save time

%time
from tqdm import tqdm_notebook

# df_new
if not os.path.exists('df_new.csv'):
    df_new = df.copy()
else:
    df_new = pd.read_csv('df_new.csv')
print(df_new.head())


for i in range(3, 5):
    if mul_per_c[i] <= 1:
        continue

    data = df[df['train_y'] == i]
    for j in tqdm_notebook(range(len(data))):
        img_path = data['train_x'].values[j]
        print('\n\n Dealing ', img_path)

        suffix = ''
        if '.png' in img_path:
            suffix='.png'
        else:
            suffix='.jpeg'

        img = cv2.imread(img_path)


        ## find dark image and adjust their brightness
        b = detect_brightness(img)
        threshold = 50
        if b < threshold:
            print('\n Original image is too dark')

        initial_coef = 1.8
        while b < threshold:
            img = brighten(img, initial_coef)
            b = detect_brightness(img)
            initial_coef = initial_coef + 0.2

        cv2.imwrite(img_path, img)
        if b >= threshold:
            print('Brightened! ', b, initial_coef)


        plt.imshow(img)

        ## horizontal flip
        result1 = cv2.flip(img, 0)
        idx1 = df[df['train_x'] == img_path].index.values[0] + 1
        img_name1 = os.path.splitext(img_path)[0]+'_flip_h'+suffix
        cv2.imwrite(img_name1, result1) # new image 
        df_new = insert_row(df_new, idx1, img_name1, i) # insert 
        print(img_name1)


        ## vertical flip
        result2 = cv2.flip(img, 1)
        idx2 = df[df['train_x'] == img_path].index.values[0] + 2
        img_name2 = os.path.splitext(img_path)[0]+'_flip_v'+suffix
        cv2.imwrite(img_name2, result2) # new image 
        df_new = insert_row(df_new, idx2, img_name2, i) # insert 
        print(img_name2)


        ## both flip
        result3 = cv2.flip(img, -1)
        idx3 = df[df['train_x'] == img_path].index.values[0] + 3
        img_name3 = os.path.splitext(img_path)[0]+'_flip_b'+suffix
        cv2.imwrite(img_name3, result3) # new image 
        df_new = insert_row(df_new, idx3, img_name3, i) # insert 
        print(img_name3)

        if mul_per_c[i] <= 4:
            continue



df_new.to_csv('df_new.csv', index=False)

在上面的代码中,我也尝试过plt.imshow(img),但没有图像显示。 在此处输入图像描述

标签: python

解决方案


推荐阅读