0

I am trying to save sns matplotlib output as jpg file and reopen it with cv2.

but i am facing distinct data loss, would someone help me to resolve, i tried in several savefig options and documentations.

sample code

import pandas as pd
import numpy as np
import cv2
import seaborn as sns
import matplotlib.pyplot as plt
by_c = None

fig = plt.Figure(figsize=(5, 4), dpi=100)
g = sns.FacetGrid(pd.DataFrame(np.random.random(10)*150, columns=['col']), col=None,  row=None, height=3.5, aspect=1)
g.map_dataframe(sns.histplot, x='col')
plt.title('col'+' - '+str(by_c)+'-', fontsize=12)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.savefig('temp.png')
plt.show()

Out:

enter image description here

Saved picture example of 'temp.png'

Saved Picture of temp.png
out:

reopening image

im = cv2.imread('temp.png')
plt.imshow(im)

Out1: Image title and lables sliced bit, i am not sure how else i can save it. Would someone please help to resolve it

enter image description here

Naga kiran
  • 4,528
  • 1
  • 17
  • 31

1 Answers1

1

To set the quality of the image use the dpi, and also specify the bbox_inches for a full layout. If not, it will consider the nearest view of the image

import pandas as pd
import numpy as np
import cv2
import seaborn as sns
import matplotlib.pyplot as plt
by_c = None

fig = plt.Figure(figsize=(5, 4), dpi=100)
g = sns.FacetGrid(pd.DataFrame(np.random.random(10)*150, columns=['col']), col=None,  row=None, height=3.5, aspect=1)
g.map_dataframe(sns.histplot, x='col')
plt.title('col'+' - '+str(by_c)+'-', fontsize=12)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.savefig('temp.png',dpi=300, bbox_inches = "tight")
#plt.savefig('temp.png')
plt.show()

im = cv2.imread('temp.png')
plt.imshow(im)

Resultant Image:

resultant image

Roxy
  • 1,015
  • 7
  • 20