在 Python 中拆分和合并图像

use*_*264 1 python image-processing histogram scipy

我正在尝试使用 python 中的图像切片器分割图像,然后对每个图像应用直方图均衡化并将它们组合回来。我能够将图像分成更小的块,我可以看到它们正在更新,但在将它们拼接在一起后,我最终得到了与原始图像相同的图像。有人可以指出我做错了什么。文件名为 watch.png

import cv2
import numpy as np
from matplotlib import pyplot as plt
from scipy.misc import imsave
# import scipy
from scipy import ndimage
from scipy import misc
import scipy.misc
import scipy

import sys
import argparse
import image_slicer
from image_slicer import join


img = 'watch.png'
num_tiles = 64
tiles = image_slicer.slice(img, num_tiles)



file = "watch"
k = 0
filelist =[]
for i in range(1,9):
    for j in range(1,9):
        filelist.insert(k, file+"_"+str(i).zfill(2)+"_"+str(j).zfill(2)+".png")
        k=k+1

for i in range(0,num_tiles):
    img = scipy.misc.imread(filelist[i])
    hist,bins = np.histogram(img.flatten(),256,[0,256])
    cdf = hist.cumsum()
    cdf_normalized = cdf *hist.max()/ cdf.max()  
    plt.plot(cdf_normalized, color = 'g')
    plt.hist(img.flatten(),256,[0,256], color = 'g')
    plt.xlim([0,256])
    plt.legend(('cdf','histogram'), loc = 'upper left')
    cdf_m = np.ma.masked_equal(cdf,0)
    cdf_o = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
    cdf = np.ma.filled(cdf_o,0).astype('uint8')
    img3 = cdf[img]
    cv2.imwrite(filelist[i],img3)


image = join(tiles)
image.save('watch-join.png')
Run Code Online (Sandbox Code Playgroud)

Joh*_*anL 5

查看image_slicer代码后,我可以看到混乱。主要问题是每个Tile对象都包含图像数据和元数据,例如文件名和最终图像中的位置。但是,当指向的文件更新时,图像数据不会更新。

因此,当更新元数据指向的文件时,图块的图像对象也需要更新。我想最简单的方法是在磁盘上的文件发生更改时重新打开磁贴中的图像。这很可能可以解决问题:

import cv2
import numpy as np
from matplotlib import pyplot as plt
from scipy.misc import imsave
from scipy import ndimage
from scipy import misc
import scipy.misc
import scipy
import image_slicer
from image_slicer import join
from PIL import Image

img = 'watch.png'
num_tiles = 64
tiles = image_slicer.slice(img, num_tiles)

for tile in tiles:
    img = scipy.misc.imread(tile.filename)
    hist,bins = np.histogram(img.flatten(),256,[0,256])
    cdf = hist.cumsum()
    cdf_normalized = cdf *hist.max()/ cdf.max()  
    plt.plot(cdf_normalized, color = 'g')
    plt.hist(img.flatten(),256,[0,256], color = 'g')
    plt.xlim([0,256])
    plt.legend(('cdf','histogram'), loc = 'upper left')
    cdf_m = np.ma.masked_equal(cdf,0)
    cdf_o = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
    cdf = np.ma.filled(cdf_o,0).astype('uint8')
    img3 = cdf[img]
    cv2.imwrite(tile.filename,img3)
    tile.image = Image.open(tile.filename)

image = join(tiles)
image.save('watch-join.png')
Run Code Online (Sandbox Code Playgroud)

因此,主要的变化是tile.image = Image.open(tile.filename)在循环的末尾添加。另请注意,我通过删除生成文件名的第一个循环来稍微更新您的代码,而第二个循环直接在图块上进行,因为它们包含所有准备好的所需信息。