简体   繁体   中英

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()

i made gradient magnitude image and then i made concatenated image as input image and gradient image, i want to save concatenated image but why opencv didnt save concatenated image, it saved input image i got error an cv2.imwrite

enter image description here

If you want to show original image and gradient magnitude side-by-side (as in the attached image), np.concatenate should be used with axis=1 , not 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)

As is, you are concatenating along the channel dimension, and ending up with a 4 channel image.

On the other hand, if that's the intention -- if you want to save a BGRA image with gradient magnitude as an alpha channel -- you might consider saving the image as a .png , rather than .jpg .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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