[Opencv + python] Digital Image Processing Course Design: Color image restoration

     This article Wuhan University of Technology Digital Image Processing Course Design: implementation process color image restoration, I am a novice Python, understanding of digital image processing is limited to the scope of the classroom, at any inadequacies in welcome that.

       First the renderings for the jpg image, processing is completed within one minute, the following are the image after the original image, color image, automatic cutting and other optimization.

                                                                           

 

       For tif images are processed within three minutes, the following are the images of the original picture, color image, cutting and other optimization. (Original is 60MB, upload pictures here about the size of 2MB, only for effect reference)

 

 

 

  • SUMMARY description

1. The background to the issue

        Sergei Mikhailovich Prokudin-Gorskii (1863-1944) was a man beyond their age, as early as 1907, he was convinced that color photography will be the future trend of development. At the time, due to the special permission of the Czar, he can travel around the vast Russian empire and take what he saw, including the only color portrait of Leo Tolstoy. He took a lot of color photography with simple primitive law: people, architecture, landscape, railways, bridges ......!

Their use in color photography method is very simple: each red, green, and blue filters for each scene of the three exposures is recorded onto a glass substrate, and envisages the backsheet superposed three colors through a special projection display apparatus, so that the audience can understand this vast country through color photos. Unfortunately, his plan never materialized: he left Russia after the 1918 October Revolution, never to return. Fortunately, RGB glass plate negatives of Tsarist empire last years of his shot survived, and was bought by the Library of Congress (LoC) in 1948. LoC recently negatives digitized and can be made available for public download via the network.

 

2. The design goals

      本次课程设计的目的是利用图像处理技术,基于数字化存储的玻璃底板图像自动生成尽量非虚化的彩色图像。为完成本次课程设计,你需要从原始图像文件中分割提取三个彩色通道图像,将它们对齐并彼此叠加在一起,最终形成一张RGB彩色图像。美国国会图书馆在其网站上详细说明了他们对这批照片进行复原并创建彩色图像的过程,可以参考

      http://www.loc.gov/exhibits/empire/making.html

1.设计思路

         Prokudin Gorskii将一块3英寸宽9英寸长的窄玻璃板垂直放置在相机中。然后,他用红色滤镜、绿色滤镜和蓝色滤镜以相当快的顺序拍摄了同一场景三次。通过Prokudin Gorskii的相机观看时,被拍摄的场景会出现颠倒,并与实际方向相反。对于数字处理,原始的三部分玻璃负片在灰度模式下用高架数码相机扫描。图像编辑软件将整个板的扫描从负片转换成正片。扫描被反转以表示原始物理方向。然后将整个板还原为8位灰度模式。在放大倍数下,检查板上每个图像的对比度、分色程度、乳剂损坏程度以及可能影响最终颜色合成的任何其他细节,将整个板的扫描对齐,并裁剪外侧边缘可以得到修复的彩色图片。

        类似的,我们要通过数字图像处理进行彩色图片复原,需要首先获得图片不同颜色的三个图层,在图层处于灰度模式时,将红色(R)、蓝色(B)和绿色(G)层对齐,形成“RGB”颜色组合。对齐之后将得到一副带有杂乱边框的图片,可以通过裁剪将其剪去,裁剪后的颜色组合整体调整以创建适当的对比度、适当的高光和阴影细节以及最佳的颜色平衡,最终可以完成彩色图片的恢复。

2.简易流程图

 

 

  • 实现方案

(1)读入图片:

思路描述:读入文件,若为tif文件将其转换为8位无符号整数格式,之后转换成灰度图,并保存原始图片。

关键代码:

pic_name = '../turkmen.tif'  #图片名

im =  cv.imread(pic_name)  #将图像转换为8位无符号整数格式

if '.tif' in pic_name:

    im=skimage.util.img_as_ubyte(im)

im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)

#之后会利用图片构造高斯金字塔,保留原始图片

im_old = im.copy()

(2)构造高斯金字塔。

思路描述:对于jpg文件我们可以轻松地对图像进行遍历操作,但是tif文件太大非常耗时,所以通过构造高斯金字塔的方法解决。先对图片进行高斯滤波处理以使图片即时缩小也能保留较多细节,然后再每次删除一半的行和列达到减小图片大小的效果,如图所示。

                                                        

 

关键代码:

#由于初始图像已存至变量im_old,只需保留满足大小要求的最后一层图像即可

#计算高斯核函数

    def gausskernel(size):  

    sigma=0.8

    gausskernel=np.zeros((size,size),np.float32)

    k = int(size/2)

    print(k)

    for i in range (size):

        for j in range (size):

            norm=math.pow(i-k,2)+pow(j-k,2)

            gausskernel[i,j]=math.exp(-norm/(2*math.pow(sigma,2)))    

    sum=np.sum(gausskernel)   # 求和

    kernel=gausskernel/sum   # 归一化

return kernel



def pyramid_Gauss(image):   

    kernel=gausskernel(3)        #阶数取3

    temp = image.copy() 

    (length,width) = temp.shape[:2]

    length = length / 3.0

    cnt = 0  

#当图片过大对其构造高斯金字塔使其大小小于一定限度

    while length * width > 250000 :

        cnt = cnt + 1

        temp = pyramid_Down(temp,kernel)

        (length,width) = temp.shape[:2]     

    cv.imshow("pyramid_down_" , temp)       

    return temp,cnt



def pyramid_Down(image,kernel):

    (length,width) = image.shape[:2]

    img1 = np.zeros((length,width),np.uint8)

# 高斯滤波过滤

    for i in range (1,length-1):

        for j in range (1,width-1):

            print(i,j)

            s = 0

            for k in range(-1,2):

                for l in range(-1,2):

                    s = s + image[i+k,j+l]*kernel[k+1,l+1]  

            img1[i,j] = s

   #删去一半的行和列,构造高斯金字塔1

    cnt = 0

    for i in range(length):

        if i % 2 == 1:

            img1 = np.delete(img1, i - cnt, axis=0)

            cnt = cnt + 1

    cnt = 0

    for j in range(width):    #删列操作与上文类似,在此省略

        ……

    #主函数调用上述函数完成操作

im,count = pyramid_Gauss(im)

print('pyramid finished!')

(3)计算图层相似性及平移距离

思路描述:由公式:

SSD(u,v) =  Sum{[Ima_1(u+x,v+y) – Ima_2(x,y)] ^2} 

可计算并比较图层间的相似程度。

关键代码:

def find_min_ssd(img_1,img_2,r_lim,d_lim):

      #寻找两幅图片的最小ssd所需平移的坐标

      #img_1固定,img_2平移的空间为[-r_lim,-d_lim] -> [r_lim,d_lim]

      length,width = img_1.shape[:2]



      #最小ssd初始化为无穷大

      min_ssd = float("inf")

      min_r = 0

      min_d = 0

      sum_ssd = 0

      for r_dis in range(-r_lim,r_lim+1):

          for d_dis in range(-d_lim,d_lim+1):

              sum_ssd = 0

              for i in range(length):

                  for j in range(width):

                      x = i + d_dis

                      y = j + r_dis

                      if(x >= 0 and x < length and y >= 0 and y < width):

                          sum_ssd = sum_ssd + (int(img_1[x,y])-int(img_2[i,j])) * (int(img_1[x,y])-int(img_2[i,j]))

              sum_ssd = sum_ssd

              if sum_ssd < min_ssd:

                  min_r = r_dis

                  min_d = d_dis

                  min_ssd = sum_ssd

return min_r,min_d

#在主函数中调用上述函数

height = np.floor(im.shape[0]/3.0).astype(np.int)

b = im[:height]

g = im[height:2 * height]

r = im[2 * height:3 *height]

(a1,b1) = find_min_ssd(r,b,15,15)

(a2,b2) = find_min_ssd(r,g,15,15)

#每一层高斯金字塔图片的长宽各缩小一倍,共建了count层,需要使平移参数乘上2的count次方

k = math.pow(2,count)

a1 = int(a1 * k)

b1 = int(b1 * k)

a2 = int(a2 * k)

b2 = int(b2 * k)

 

(4)平移图层,将三个图层重叠得到彩色图片。

思路描述:通过调用translate函数对图像进行仿射变化,达到平移的效果。

关键代码:

def translate(img,tx,ty):

    #图像平移

    length,width = img.shape[:2]

    m = np.float32([[1,0,tx],[0,1,ty]])

#仿射变换

    res = cv.warpAffine(img,m,(width,length))

    return res



#在主函数中调用上述函数

b = translate(b,a1,b1)

g = translate(g,a2,b2)

im_out = cv.merge((b,g,r))

print(a1,b1,a2,b2)

cv.imshow("aligned image",im_out)

cv.imwrite('../turkmen_2.tif',im_out)



 

 

五、优化方案

(1)图像微调。

思路:在得到平移距离后,因为对于.tif文件,该平移距离是通过比较压缩后的图像所得,而非原始图像,假设构建了四层金字塔,则需要对原距离乘以16,那么所得平移距离必然是16的整数倍,对于原始图像,这些点往往不是平移的最优点,在对原始图片平移前,应该对该平移距离进行微调。

关键代码:

#im_old为原始灰度图像

height = np.floor(im_old.shape[0]/3.0).astype(np.int)

b = im_old[:height]

g = im_old[height:2 * height]

r = im_old[2 * height:3 *height]

print(b.shape)

#find_min_ssd_adj逻辑与find_min_ssd相同,只是搜索空间为原始图像,且平移距离仅为之前所得平移距离的领域,l1,l2,l3,l4为常数可根据实际情况修改

(a1,b1) = find_min_ssd_adj(r,b,a1-l1,a1+l1,b1-l2,b1+l2)

(a2,b2) = find_min_ssd_adj(r,g,a2-l3,a2+l3,b2-l4,b2+l4)

(2)改进相似度比较策略。

思路: 在使用上文的算法进行处理后,即使对jpg图片,对齐效果依然不能算完美,如cathedral.jpg图片放大后蓝色图层存在一定偏移,需要人工对距离进行一定微调,于是我输出了人工调整后的SSD总和与之前计算的最优SSD总和进行比较,发现调整后的SSD和反而增加了,证明我的算法没有错误,但调整后的对齐效果确实更好。

      经过仔细思考,我发现原始图片四周存在黑边,当对某一个图层进行平移后,可能会使得某一图层的非黑边部分与另一图层黑边部分产生更多重叠,因为黑边的亮度接近0,在这部分计算相似度可能会产生较大的SSD和,使得全局比较并累加得到的平移距离往往比真实应该平移的距离偏小。

      于是对比较策略进行调整,如果当待比较的点距离上、下、左、右边界较近(本课程设计中设为距离小于1/6长或宽),则其值不计入SSD总和,否则计入总和,即人为设定一条阈值,只计算图片中间部分的点进行比较相似度,虽然一定程度上减少了比较的面积,但通过尝试对不同图像进行实验,得到的效果非常好,且算法运行速度大大提高。

       具体代码即为在之前的for循环加一个条件判断即可,在此不再赘述。

 

(3)提高对比度。

思路:在合成彩色图片前,对图像的亮度进行重新标定是常用的处理手法。本课程设计中,在平均亮度最暗的颜色通道上,其接近最黑的像素(取与最黑像素值之差小于10的点)被标定为0,在平均亮度最亮的颜色通道上,其接近最亮的像素(同上)被标定为255

关键代码:

def contrast(r1,b1,g1):

    (length1,width1) = r1.shape[:2]

    sum_b = 0

    sum_g = 0

    sum_r = 0

    for i in range(length1):

        for j in range(width1):

            sum_b += r1[i,j]

            sum_g += b1[i,j]

            sum_r += g1[i,j]

    if(sum_b > sum_g and sum_g > sum_r):

        i_max = b1

        i_min = r1

    elif(sum_b > sum_g and sum_r > sum_g):

#判断哪个图层平均亮度最大和最小,与上述代码类似,在此省略

    maxn = -1    

    minn = 256

    for i in range(length1):

        for j in range(width1):

            if(i_max[i,j] > maxn):

                maxn = i_max[i,j]

            if(i_min[i,j] < minn):

                minn = i_min[i,j]

    for i in range(length1):

        for j in range(width1):              

            if(i_max[i,j] >= maxn - 10):    

                i_max[i,j] = 255

    for i in range(length1):

        for j in range(width1):

            if(i_min[i,j] <= minn + 10):

                i_min[i,j] = 0

    return r1,b1,g1

 

(4)自动裁剪边框。

思路:在进行自动裁边前,我观察到边框的颜色很怪异,可能导致在边框不同图层像素值之间差很大,于是我将图片每一行(列)的不同图层像素值最大的差输出,观察到在边框附近这个差值远大于图片内部,即可以通过设定一个阈值将差值大于阈值的行(列)删除,达到自动裁边的效果。

关键代码:
 

#删除列的代码与删除行的逻辑相同,以下代码省略删除列的部分代码

up_record = 0     #上边界,小于其的行将被删除,以下类似

down_record = 999999999    #下边界

for i in range(length):    #计算上下边界

    sum_t = 0

    for j in range(width):

        sum_t += max(b[i,j],g[i,j],r[i,j]) - min(b[i,j],g[i,j],r[i,j])

    if(sum_t/width > 65 and i <length/4):

        up_record = i

    elif(sum_t/width > 65 and i > 3 * length / 4 and down_record > i ):

        down_record = i

    #删除行,删除列代码已省略

for i in range(length - down_record):  

    b = np.delete(b,-1,axis = 0)

    g = np.delete(g,-1,axis = 0)

    r = np.delete(r,-1,axis = 0)

for i in range(up_record):

    b = np.delete(b,0,axis = 0)

    g = np.delete(g,0,axis = 0)

    r = np.delete(r,0,axis = 0) 

im_out = cv.merge((b,g,r))

六、其他改进

特征点匹配

         基于对课程设计任务的理解,采用了模板匹配的方式进行特征匹配,模板匹配是一种最原始、最基本的模式识别方法,研究某一特定对象物的图案位于图像的什么地方,进而识别对象物。它是图像处理中最基本、最常用的匹配方法。模板匹配具有自身的局限性,因为它只能进行平行移动,但是对于本次课程设计来说非常适合。

 

关键代码:

b = im[:height]

g = im[height:2 * height]

r = im[2 * height:3 *height]

raw = g



#选取某图层部分区域充当模板

template = b

(l1,l2,w1,w2)=(50,150,200,300)

template = template[l1:l2,:]

template = template[:,w1:w2]

cv.imshow("test",template)

height, width = template.shape[:2]



#使用归一化平方差匹配法进行模板匹配

result = cv.matchTemplate(raw,template,cv.TM_SQDIFF_NORMED)



#进行归一化

cv.normalize( result, result, 0, 1, cv.NORM_MINMAX, -1 )

min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)



a1 = min_loc[0]-w1

b1 = min_loc[1]-l1

#得到该图层平移距离,再对另外一个图层做相同操作后调用前文中的代码进行平移,并将平移后的图层重叠即可恢复彩色图像。

 

  • 问题与影响因素讨论

 

1.结果描述

        程序经过调试与修改,对所给的每张图片都能恢复成效果较好的彩色图片,对jpg图片能够在2分钟左右完成,对于tif图片能够在5分钟左右完成,且能对不同颜色的边框进行自动裁剪。

2.综合分析

         要对彩色图像进行恢复,首先需要获得图片不同颜色的三个图层,在图层处于灰度模式时,将红色(R)、蓝色(B)和绿色(G)层对齐,形成“RGB”颜色组合。对齐之后将得到一副带有杂乱边框的图片,可以通过裁剪将其剪去,裁剪后的颜色组合整体调整以创建适当的对比度、适当的高光和阴影细节以及最佳的颜色平衡,最终可以完成彩色图片的恢复。

         本次课程设计所实现的程序,对jpg图片处理较快,大约在一分钟之内可以完成,对tif图片,因为对tif图片构造高斯金字塔的图片进行对齐后,为了对原始图片进行对齐,还对原始的三个图层进行了小范围的微调,所以处理时间大约在三分钟,考虑到图片的大小,这个时间我认为还在可以接受的范围内,后续可以考虑对循环体进行结构的优化,以减少运行的时间。    

  • 参考文献

 

[1]Brooks, L.E.. The empire that was Russia: the Prokudin-Gorskii photographic record re-created[P]. Applied Imagery Pattern Recognition Workshop, 2002. Proceedings. 31st,2002.

[2]Rafael C.Gonzalez Richard E.woods.数字图像处理(第三版)[M].电子工业出版社:北京,2013:1.

 

 

 

 

 

发布了38 篇原创文章 · 获赞 7 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_41514794/article/details/104686570