我有這組影像,我想從中創建一組步幅為 128 * 128 的子影像,原始影像必須大于此大小(行和列),我創建了以下函式:
def sliding_window(image, stride, imgSize):
height, width, _ = image.shape
img = []
a1 = list(range(0, height-imgSize stride, stride))
a2 = list(range(0, width-imgSize stride, stride))
if (a1[-1] imgSize != height):
a1[-1] = height-imgSize
if (a2[-1] imgSize != width):
a2[-1] = width-imgSize
for y in a1:
for x in a2:
im1 = image[y:y imgSize, x:x imgSize, :]
img.append(np.array(im1))
return img
以及我稱之為定義的主要代碼片段:
im_counter = 0
image_data = []
image_label = []
for cl in file_images:
for img_file in data[cl]:
path = img_path cl "/" img_file
im = image.load_img(path)
im = image.img_to_array(im)
im_counter = 1
if(im_counter % 500 == 0):
print("{} images processed...".format(im_counter))
if (im.shape[0] >= SIZE and im.shape[1] >= SIZE):
img = sliding_window(im, STRIDE, SIZE)
for i in range(len(img)):
if(img[i].shape[2] >=3):
temp_img = img[i]
temp_img = preprocess_input(temp_img)
image_data.append(temp_img)
del temp_img
gc.collect()
image.append(class_dictionary[cl])
現在,上面的代碼片段僅在 3000 張影像上運行需要永遠(僅使用 1 個 CPU 內核至少需要 25 小時),我想讓它更快,我可以訪問服務器,CPU 有很多內核,所以請您建議它的并行版本,以便它運行得更快?
注意:從原始影像回傳的子影像序列非常重要,不允許任意影像序列。
uj5u.com熱心網友回復:
這是您可以嘗試的內容的粗略概述。
def main():
# Create a list of tuples consisting of the file path, and the class
# dictionary info for each of the cl arguments
args = []
for cl in file_images:
for img_file in data[cl]:
path = img_path cl "/" img_file
args.append((path, class_dictionary[cl]))
with multiprocessing.Pool(processes=30) as pool: # or however many processes
image_counter = 0
# Use multiprocessing to call handle_on_image(pathname, info)
# and return the results in order
for images, info in pool.starmap(handle_one_image, args):
# Images is a list of returned images. info is the class_dictionary info that we passed
for image in images:
image_counter = 1
image_data.append(image)
image_label.append(info)
def handle_one_image(path, info):
image_data = []
im = image.load_img(path)
im = image.img_to_array(im)
if (im.shape[0] >= SIZE and im.shape[1] >= SIZE):
img = sliding_window(im, STRIDE, SIZE)
for i in range(len(img)):
if(img[i].shape[2] >=3):
temp_img = img[i]
temp_img = preprocess_input(temp_img)
image_data.append(temp_img)
return image_data, info
else:
# indicate that no images are available
return [], info
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352468.html
下一篇:如何使用GIMP防止色帶?
