繁体   English   中英

图像变换后 opencv cv2.imwrite 错误

[英]opencv cv2.imwrite error after image transform

import cv2
import numpy as np

def prepare_data_test(test_path):
    input_names = []
    for dirname in test_path:
        for _, _, fnames in sorted(os.walk(dirname)):
            for fname in fnames:
                if is_image_file(fname):
                    input_names.append(os.path.join(dirname, fname))
    return input_names

def is_image_file(filename):
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)

IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]

test_path = ["./figures/"]  # ["./test_images/real/"]
subtask = "dataset"  # if you want to save different testset separately
val_names = prepare_data_test(test_path)
num=1
for val_path in val_names:
    im = cv2.imread(val_path)#3채
    img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)  # no channel
    dx = cv2.Sobel(img, cv2.CV_32F, 1, 0)  # float 형태의 미분값을 저장
    dy = cv2.Sobel(img, cv2.CV_32F, 0, 1)

    mag = cv2.magnitude(dx, dy)  # gradient magnitude , no channel
    mag = np.clip(mag, 0, 255).astype(np.uint8)  # 255보다 커질 수 있으므로 saturate 연산
    #mag = np.expand_dims(mag, axis=2)

    mag = cv2.cvtColor(mag, cv2.COLOR_GRAY2RGB)  # convert mag to RGBA 채널: 3
    mag = cv2.cvtColor(mag, cv2.COLOR_RGB2GRAY) #width, height 채널 없어짐
    mag = np.expand_dims(mag, axis=2)
    print(mag.shape)

    #concat = np.concatenate([im,mag],-1)
    concat = np.concatenate([im,mag], axis = 2)
    outfile = 'output%s.jpg' % (num)
    cv2.imwrite(outfile, concat)##### it saved im image  error
    num = num + 1
cv2.waitKey()
cv2.destroyAllWindows()

我制作了梯度幅度图像,然后我制作了连接图像作为输入图像和梯度图像,我想保存连接图像但是为什么 opencv 没有保存连接图像,它保存了输入图像我得到了错误 cv2.imwrite

在此处输入图像描述

如果要并排显示原始图像和梯度幅度(如附图所示), np.concatenate应与axis=1一起使用,而不是与axis=2一起使用:

# Convert gradient magnitude to BGR so make shape compatible with im's shape.
mag_vis = cv2.cvtColor(mag, cv2.COLOR_GRAY2BGR) 
concat = np.concatenate([im, mag_vis], axis=1)

照原样,您沿着通道维度连接,并最终得到一个 4 通道图像。

另一方面,如果这是有意的——如果你想将具有梯度幅度的 BGRA 图像保存为 alpha 通道——你可能会考虑将图像保存为.png ,而不是.jpg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM