首页 > 解决方案 > 加入提取/分割的补丁以重建图像

问题描述

我使用下面的代码从图像中提取补丁。

提取代码:

import os
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = None # to avoid image size warning

imgdir = "/path/to/image/folder"
filelist = [f for f in glob.glob(imgdir + "**/*.png", recursive=True)]
savedir = "/path/to/image/folder/output"

start_pos = start_x, start_y = (0, 0)
cropped_image_size = w, h = (256, 256)

for file in filelist:
    img = Image.open(file)
    width, height = img.size

    frame_num = 1
    for col_i in range(0, width, w):
        for row_i in range(0, height, h):
            crop = img.crop((col_i, row_i, col_i + w, row_i + h))
            name = os.path.basename(file)
            name = os.path.splitext(name)[0]
            save_to= os.path.join(savedir, name+"_{:03}.png")
            crop.save(save_to.format(frame_num))
            frame_num += 1

现在我想从之前提取的所有这些补丁中重建这个图像,我尝试了 2 个不同的代码,所以我的数据库是 120x256x256x3 提取的补丁,有 120 个补丁适合 3840x2048 形状..:

patches = []
for directory_path in glob.glob('D:\join_exemplo'):
    for img_path in glob.glob(os.path.join(directory_path, "*.png")):
        img = cv2.imread(img_path,1)
        patches.append(img)
input_patches = np.array(patches)

首先我尝试了 sklearn.feature_extraction.image 导入reconstruct_from_patches_2d,但得到了黑色图像:

reconstruct = reconstruct_from_patches_2d(input_patches, input_image)
reconstruct = reconstruct.astype(np.uint8)
Image.fromarray(reconstruct, 'RGB').save(r'D:\join_exemplo\re\re3.png')

也试过了,这在下面,但得到了灰度色调图案图像


input_image = (3840,2048,3)
reconstructed_arr = np.zeros(shape=(3840,2048,3))


#%%

>>> step = 256
>>> for x in range(img.shape[0]):
        for y in range(img.shape[1]):
            x_pos, y_pos = x * step, y * step
            reconstructed_arr[x_pos:x_pos + 512, y_pos:y_pos + 512] = img[x, y, 0, ...]
>>> (input_image == reconstructed_arr).all()
True


cv2.imwrite(r'D:\join_exemplo\re\re.png',reconstructed_arr)

有人能看出什么问题吗?对不起我的英语不好

标签: pythonimage-processing

解决方案


推荐阅读