【问题标题】:opencv cv2.imwrite error after image transform图像转换后的opencv cv2.imwrite错误
【发布时间】:2021-05-29 13:19:26
【问题描述】:
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

enter image description here

【问题讨论】:

  • 首先你的outfile在保存之前是什么形状的?其次,您得到的错误是什么?
  • im = chanel-3,mag = channel-1,concat = channel-4,我没有错误,我的问题只是图像不同 cv2.imwrite(concat) 和 concat

标签: python opencv image-processing


【解决方案1】:

如果要并排显示原始图像和梯度幅度(如附图所示),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

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2017-11-17
    • 2020-02-27
    • 1970-01-01
    • 2018-01-05
    • 2020-12-13
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多