2015-03-02 151 views
3

我的程序根据比例参数摄入图像并将图像裁剪成单独的图像,例如。 scale = 3会产生9个相同大小的图像。然后,我计算每个裁剪图像的均值rgb,并将图像中的所有像素值设置为平均rgb值。将图像拼接在一起Opencv -Python

我想知道如何将裁剪后的图像拼接在一起以输出一个图像?在这种情况下,它将是九种不同颜色的网格。

这里是我的代码:

# import packages 
import numpy as np 
import cv2 
import dateutil 
import llist 
from matplotlib import pyplot as plt 
import argparse 

#Read in image 
img = cv2.imread('images/0021.jpg') 

scale = 3 
#Get x and y components of image 
y_len,x_len,_ = img.shape 

mean_values = [] 
for y in range(scale): 
    for x in range(scale): 
     #Crop image 3*3 windows 
     cropped_img=img[(y*y_len)/scale:((y+1)*y_len)/scale, 
          (x*x_len)/scale:((x+1)*x_len)/scale] 

     mean_val=cv2.mean(cropped_img) 
     mean_val=mean_val[:3] 
     #Set cropped img pixels equal to mean RGB 
     cropped_img[:,:,:] = mean_val 

     cv2.imshow('cropped',cropped_img) 
     cv2.waitKey(0) 

     #Print mean_values array 
     #mean_values.append([mean_val]) 
#mean_values=np.asarray(mean_values) 
#print mean_values.reshape(3,3,3) 

目前的情况是嵌套用于在图像循环迭代,并输出图像,我想将它们拼接在一起(这仅仅是一个颜色的块)的顺序,但我不知道如何实现这一点。

+0

不要 “缝” - 这是更难。用所需的最终尺寸创建一个新图像,然后使用[numpy的索引功能]将每个子图像复制到最终图像的相应区域(http://docs.scipy.org/doc/numpy/user/basics.indexing.html )('cv2'图像只是'numpy'a阵列) – goncalopp 2015-03-02 15:59:14

+0

@goncalopp我会如何'复制'每个子图像到一个新的图像?它将不得不在for循环中进行,并且在每次迭代中,新的子图像将被添加到输出图像。 – 2015-03-02 16:18:37

+0

既然你做了'cropped_img = img [...]',然后在'cropped_image'上操作,原来的'img'将会被改变。在numpy数组中切片不会创建新的数组。因此,你的拼接应该已经实现了。 – 2015-03-02 16:26:02

回答

2

我不知道在OpenCV中是否存在这样的事情,但在ImageMagick中,您可以简单地调整图像的大小,使其小到大小(这将隐式平均像素),并将图像重新缩放到没有插值的原始大小 - 也叫最近邻居重新取样。就像这样:

enter image description here

# Get original width and height 
identify -format "%wx%h" face1.jpg 
500x529 

# Resize down to, say 10x10 and then back up to the original size 
convert face1.jpg -resize 10x10! -scale "${geom}"! out.jpg 

enter image description here

每原来的3×3变为:

convert face1.jpg -resize 3x3! -scale "${geom}"! out.jpg 

enter image description here

和3x5的变成:

convert face1.jpg -resize 3x5! -scale "${geom}"! out.jpg 

enter image description here