utengr
utengr

Reputation: 3355

How to write multiple images (subplots) into one image

I have two images that I would like to save as subplots in one image.

My current code works fine to display them as subplots.

import cv2 as cv
from matplotlib import pyplot as plt
image1 = cv.imread('someimage')
image2 = cv.imread('anotherimage')
plt.subplot(1, 2, 1), plt.imshow(image1, 'gray')
plt.subplot(1, 2, 1), plt.imshow(image2, 'gray')
plt.show()

OpenCV imwrite can't work in its simple form as it expects one image as input. I would like to save these subplots in one image for later visual analysis. How can I achieve this?

It can be side by side or on top of each other. Just an example :)

Two images in one

The example is just for demonstration purposes. I should be able to save multiple images into one the way like creating a subplot(x,y). For example,

enter image description here

Upvotes: 3

Views: 15910

Answers (4)

rpb
rpb

Reputation: 3299

Another solution based on add_subplot.

I prefer to use add_subplot due to its ability to create complex plot

import matplotlib.pyplot as plt

import numpy as np

ls_image_pt=['path1.jpg','path2.jpg']
for idx, dpath in enumerate(ls_image_pt):
    sub1 = fig.add_subplot(2, 2, idx + 1)
    image2 = cv.imread('dframe_0.png')
    sub1.imshow(image2, 'gray')


plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[])
plt.tight_layout()
plt.show()

Upvotes: 0

utengr
utengr

Reputation: 3355

Just for other readers: One can simply use matplotlib.pyplot.savefig. It saves the subplots exactly the way its displayed with plt.show().

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

For two images, the other two answers can be used too, I guess.

Resultant code should look this:

import cv2 as cv
from matplotlib import pyplot as plt
image1 = cv.imread('someimage')
image2 = cv.imread('anotherimage')
plt.subplot(1, 2, 1), plt.imshow(image1, 'gray')
plt.subplot(1, 2, 2), plt.imshow(image2, 'gray')
plt.savefig('final_image_name.extension') # To save figure
plt.show() # To show figure

Upvotes: 7

RMS
RMS

Reputation: 1430

import cv2 as cv
from matplotlib import pyplot as plt
image1 = cv.imread('someimage')
image2 = cv.imread('anotherimage') 
final_frame = cv.hconcat((image1, image2)) # or vconcat for vertical concatenation
cv.imwrite("image.png", final_frame)

Upvotes: 3

Jeru Luke
Jeru Luke

Reputation: 21223

You could use numpy.concatenate for this purpose:

import numpy as np
import cv2
image1 = cv.imread('someimage')
image2 = cv.imread('anotherimage')
final = np.concatenate((image1, image2), axis = 0)
cv2.imwrite('final.png', final)

axis = 0 concatenates images vertically

axis = 1 concatenates images horizontally

Upvotes: 1

Related Questions