我制作了一个程序,其中包含一个图像文件夹,并且每个程序都通过img.shape
函数找到宽度。
然后,它创建一个包含以下值的dict:[(filename, width)]
。
此时如何将文件(基于我给出的形状值)移动到指定的fodlers? 我的意思是,如果我给条件一个50像素的值,我怎么能告诉程序将每个相应的图像移动到一个文件夹?
import os
import cv2
import pandas as pd
import statistics
from heapq import nsmallest
src = os.path.expanduser('~\\Desktop\\roiseparator\\roi_single\\')
imgs = os.listdir(src)
sorted_imgs = imgs.sort(key=lambda x: int(x.split('.')[0]))
lista_roi = []
lista_w = []
lista_key_value = {}
for i, roi in enumerate(imgs):
image = cv2.imread(str(src) + str(imgs[i]))
(h, w) = image.shape[:2]
lista_roi.append(i)
lista_w.append(w)
for i in range(len(lista_roi)):
lista_key_value[lista_roi[i]] = lista_w[i]
lista_key_value = list(lista_key_value.items())
print('Key - Value: ', lista_key_value)
打印结果为:[(0, 37), (1, 30), (2, 34), (3, 30), (4, 31), (5, 31), (6, 37), (7, 37), (8, 60), (9, 73), (10, 53)]
必须理解为:(filename,width)
。
输出示例:if width =< 50,将满足此条件的所有文件移动到文件夹。警告:50
不是一个稳定的值,它是一个变量,它在代码的后半部分被识别。
此时,我发现使用width ..
的值恢复文件(图像)很困难答案 0 :(得分:1)
这可能会有所帮助:
import os
from os.path import join
import cv2
src = os.path.expanduser('~\\Desktop\\roiseparator\\roi_single\\')
dest = #destination dir
width_threshold = 50
imgs = os.listdir(src)
sorted_imgs = imgs.sort(key=lambda x: int(x.split('.')[0]))
imgs_widths = []
for img_name in sorted_imgs:
image = cv2.imread(str(src) + img_name)
(h, w) = image.shape[:2]
imgs_widths.append(w)
# printing stuff
for img_name, img_width in zip(sorted_imgs, imgs_widths):
print("Image: ", img_name, "has width: ", img_width)
# set width here after watching the printed stuff
width_threshold = int(input())
# filter images based on width
for img_name, img_width in zip(sorted_imgs, imgs_widths):
if img_width > width_threshold:
old_file = join(src, img_name)
new_file = join(dest, img_name)
os.rename(old_name, new_name)
答案 1 :(得分:1)
基于tkhurana96回答,我使用shutil
模块:
import shutil
dest = os.path.expanduser('~\\Desktop\\roiseparator\\folder\\')
for imgs, img_width in zip(imgs, lista_w):
print("Image: ", imgs, "has width: ", img_width)
if img_width <= magic_number: # magic number is a variable number
shutil.move(str(src) + imgs, dest)