簡體   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