2013-10-03 187 views
0
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... 

    """ 

我使用的SRM(統計區域合併)提供包被保存由cv.SaveImage()在this page.損壞圖像中的OpenCV

我剛纔已經改變了包裝給出的示例程序。我必須將由SRM包函數返回的類型轉換爲iplimage。使用該軟件包時沒有錯誤,但在某處使用opencv函數。

這是懸掛後控制檯關閉後保存的圖像。 它使用cv.SaveImage()

After getting error

我試圖cv2.imwrite(),我得到這個作爲結果:

enter image description here

這是應該已經保存的圖像。我用scipy.misc.imsave('image.jpg', map)來保存這個。

Should have been!

+0

如果你嘗試'cv2.imwrite()'會發生什麼?你不需要轉換成'IplImage';它可以直接保存'ndarray'。 – Aurelius

+0

@Aurelius我甚至試過,但它沒有幫助,雖然控制檯沒有掛這次。我編輯了所問的問題 –

回答

2

爲什麼你使用的IplImage和PIL? SRM庫讀取numpy數組,然後從cv2.imread(image)獲得一個numpy數組,然後如果需要調整yuor圖像的大小,可以使用opencv函數cv2.resize(...)。最後,你可以保存與cv2.imwrite(...)代碼OpenCV的圖像應該出現這樣的:

import sys, cv2, numpy 
from SRM import SRM 

"""Main Program""" 

filename = "snap.jpeg" 
Q = 64 

img = cv2.imread(filename) 
name = filename[:-4] 


if img.shape[0] > 200 or img.shape[1] > 200: 
    ratio = img.shape[0] * 1./img.shape[1] 
    size = (int(ratio * 200), 200) 

    img = cv2.resize(img, size, interpolation=cv2.INTER_LANCZOS4) 

    srm = SRM(img, Q) 

    srm.initialization() 
    srm.segmentation() 
    classes, srmMap = srm.map() # Map is a python function, use different variable name 
    srmMap = srmMap.astype('uint8') # or you can try other opencv supported type 
    # I suppose that srmMap is your image returned as numpy array 
    cv2.imwrite('name.jpeg', srmMap) 
    # or 
    cv2.imshow('image', srmMap) 
    cv2.waitKey(0)