Sergio Pantano
Sergio Pantano

Reputation: 141

How to view the pyramid of images generated with OpenCV?

I need to generate a single image with the result of the pydown function (as shown in the last image), but I am not able to place the smaller images in the second column. Below is my code:

def comporImagem(piramide):
    linhas, colunas, dim = piramide[0].shape   
    imagem_composta = np.zeros((linhas, colunas + colunas // 2, dim), dtype=np.int)  
    imagem_composta[:linhas, :colunas, :] = piramide[0] 

    i_linhas = 0 

    for i in range(3):

        nova_imagem = cv2.pyrDown(piramide[i_linhas])
        linhas, colunas, dim = nova_imagem.shape

        i_linhas  = i_linhas + 1
        piramide[i_linhas] = nova_imagem
        imagem_composta[:linhas, :colunas, :] = piramide[i_linhas]

    return imagem_composta

arquivo="test"
piramide=[]
for i in range(4):
    nome=arquivo+str(i)+".jpg"
    piramide.append(cv2.imread(nome))
imagem=comporImagem(piramide)
imagem=imagem[:,:,::-1] 
plt.imshow(imagem)

the result is: wrong picture

But I need the image to look like this:

Right picture

How can I do this?

Upvotes: 1

Views: 378

Answers (1)

fmw42
fmw42

Reputation: 53247

Here is one way to do that in Python/OpenCV.

Input:

enter image description here

import cv2
import numpy as np

# set number of levels
levels = 4

# read input as img
img = cv2.imread('lena.png')
hh, ww, cc= img.shape


# create first layer of pyramid as copy of original
pyramid = [img.copy()]

# create black image of desired output size as:
# output height = height of input and output width = width + width/2 of input
outimage = np.zeros((hh, ww + ww // 2, 3), dtype=np.uint8)

# put img into outimage at top left corner
outimage[0:hh, 0:ww, :cc] = pyramid[0]

# create next level and add to pyramid and outimage
yoffset = 0
xoffset = ww
for i in range(1, levels):
    img_small = cv2.pyrDown(pyramid[i-1])
    ht, wd = img_small.shape[:2]
    pyramid.append(img_small)
    outimage[yoffset:yoffset + ht, xoffset:xoffset + wd ] = img_small
    yoffset += ht

# save resulting output
cv2.imwrite('lena_pyramid.png', outimage)

# show results
cv2.imshow('INPUT', img)
cv2.imshow('OUTPUT', outimage)
cv2.waitKey(0)


Result:

enter image description here

Upvotes: 2

Related Questions