python - 如何在for循环中将代码更改为同步模式
问题描述
我正在做 Kaggle APTOS 比赛,我想根据以下步骤平衡图像数量:
- 使太暗的图像变亮
- 水平翻转,垂直翻转,两者都基于亮化的图像
- 根据 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)
解决方案
推荐阅读
- python-3.x - How do I unstack these three histogram columns? Position Argument Fails
- excel - 找不到对象做 VBA Vlookup
- javascript - 在不同的js文件中为对象添加属性和方法
- javascript - JQuery Datepicker在一个表单上返回空但不是其他表单
- angular - 当购物车中的产品数量增加时,总价不更新在离子电子商务应用程序中
- java - 如何停止/控制 AWS S3 在对象上传时触发的事件以调用 AWS Lambda?
- fbx - 通过python sdk将fbx转换为obj并且obj的正常是错误的
- hadoop - hadoop.tmp.dir的VERSION文件有什么用
- angular - 带有角度 4 md-select 的两种方式数据绑定恐怖
- php - Sendbird/Guzzle 返回“请求正文是无效的 JSON”