gpt4 book ai didi

python - cv.SaveImage()在opencv中保存的损坏的图像

转载 作者:行者123 更新时间:2023-12-02 17:14:08 26 4
gpt4 key购买 nike

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数组,然后,如果需要调整图像大小,则可以使用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)

关于python - cv.SaveImage()在opencv中保存的损坏的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com