import sys, Image, scipy, cv2, numpy
from scipy.misc import imread
from cv2 import cv
from SRM import SRM
def ndarrayToIplImage (source):
"""Conversion of ndarray to iplimage"""
image = cv.CreateImageHeader((source.shape[1], source.shape[0]), cv.IPL_DEPTH_8U, 3)
cv.SetData(image, source.tostring(), source.dtype.itemsize * 3 * source.shape[1])
return image
"""Main Program"""
filename = "snap.jpeg"
Q = 64
im = imread(filename)
name = filename[:-4]
img = Image.fromarray(im)
if img.size[0] > 200 or img.size[1] > 200:
ratio = img.size[0]/img.size[1]
size = int(ratio*200), 200
img = numpy.array(img.resize(size, Image.ANTIALIAS))
srm = SRM(img, Q)
srm.initialization()
srm.segmentation()
classes, map = srm.map()
"""Converting ndarray to PIL Image to iplimage"""
pil_img = Image.fromarray(map)
cv_img = cv.CreateImageHeader(pil_img.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_img, pil_img.tostring(), pil_img.size[0]*3)
print type(cv_img) ##prints <type 'cv2.cv.iplimage'>
"""Using ndarrayToIplImage function also gives the same error!"""
"""
cv_img if of type iplimage but still gives error while using cv.ShowImage()
or cv.SaveImage().
There is no error displayed. Just the console hangs...
"""
我使用的是this page.上提供的SRM(统计区域合并)包
我刚刚更改了包中给出的示例程序。我不得不将SRM包函数返回的类型转换为iplimage
。使用这个包没有错误,但是在使用opencv函数时会有错误。在
这是挂起后控制台关闭后保存的图像。
它使用了cv.SaveImage()
。在
我尝试了cv2.imwrite()
,结果是:
这是应该保存的图像。我用scipy.misc.imsave('image.jpg', map)
来保存这个。在
为什么要使用IplImage和PIL?SRM库读取numpy数组并从
cv2.imread(image)
获得numpy数组,如果需要调整yuor图像的大小,可以使用opencv函数cv2.resize(...)
。最后,您可以使用cv2.imwrite(...)
用opencv保存图像,您的代码应该如下所示:相关问题 更多 >
编程相关推荐