27
from scipy.misc import imread
from matplotlib import pyplot

import cv2
from cv2 import cv

from SRM import SRM ## Module for Statistical Regional Segmentation

im = imread("lena.png") 
im2 = cv2.imread("lena.png")
print type(im), type(im2), im.shape, im2.shape 
## Prints <type 'numpy.ndarray'> <type 'numpy.ndarray'> (120, 120, 3) (120, 120, 3)

srm = SRM(im, 256)
segmented = srm.run()

srm2 = SRM(im2, 256)
segmented2 = srm2.run()

pic = segmented/256
pic2 = segmented2/256

pyplot.imshow(pic)
pyplot.imsave("onePic.jpg", pic)

pic = pic.astype('uint8')
cv2.imwrite("onePic2.jpg", pic2)

pyplot.show()

onePic.jpg给出正确的分割图像,但onePic2.jpg给出完整的黑色图像。将数据类型转换为uint8usingpic = pic.astype('uint8')没有帮助。我仍然给出黑色图像!

onePic.jpg 使用pyplot.imsave()

在此处输入图像描述

onePic2.jpg 使用cv2.imwrite()

在此处输入图像描述

请帮忙!

4

2 回答 2

40

在转换pic为之前uint8,您需要将其乘以 255 以获得正确的范围。

于 2013-10-08T06:12:41.450 回答
6

尽管我同意@sansuiso,但在我的情况下,我发现了一个可能的边缘情况,即我的图像在比例上移动了一点或向下移动了一点。

由于我们正在处理无符号整数,因此单个移位意味着可能的下溢/溢出,这可能会破坏整个图像。

我发现 cv2 的 convertScaleAbs 的 alpha 值为 255.0 以产生更好的结果。

def write_image(path, img):
    # img = img*(2**16-1)
    # img = img.astype(np.uint16)
    # img = img.astype(np.uint8)
    img = cv.convertScaleAbs(img, alpha=(255.0))
    cv.imwrite(path, img)

这个答案更详细。

于 2019-10-16T02:03:23.337 回答