[python] matplotlib에서 저장된 이미지 주위의 공백 제거

이미지를 가져 와서 일부 프로세스 후에 저장해야합니다. 그림을 표시하면 그림이 잘 보이지만 그림을 저장 한 후 저장된 이미지 주위에 공백이 생겼습니다. 방법에 대한 'tight'옵션을 시도했지만 savefig작동하지 않았습니다. 코드:

  import matplotlib.image as mpimg
  import matplotlib.pyplot as plt

  fig = plt.figure(1)
  img = mpimg.imread(path)
  plt.imshow(img)
  ax=fig.add_subplot(1,1,1)

  extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
  plt.savefig('1.png', bbox_inches=extent)

  plt.axis('off')
  plt.show()

그림에 NetworkX를 사용하여 기본 그래프를 그려 저장하려고합니다. 그래프가 없으면 작동한다는 것을 알았지 만 그래프를 추가하면 저장된 이미지 주위에 공백이 생깁니다.

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1,3)
G.add_edge(1,2)
pos = {1:[100,120], 2:[200,300], 3:[50,75]}

fig = plt.figure(1)
img = mpimg.imread("C:\\images\\1.jpg")
plt.imshow(img)
ax=fig.add_subplot(1,1,1)

nx.draw(G, pos=pos)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches = extent)

plt.axis('off')
plt.show()



답변

“솔루션”이 왜 또는 어떻게 작동하는지 정확히 알 수는 없지만, 이것은 흰 여백이없는 몇 개의 에어로 포일 섹션의 개요를 PDF 파일로 플롯하려고 할 때해야 할 일입니다. (필자는 -pylab 플래그와 함께 IPython 노트북 내에서 matplotlib를 사용했습니다.)

plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = 'tight',
    pad_inches = 0)

이 부분의 다른 부분을 비활성화하려고 시도했지만 항상 어딘가에 흰색 여백이 생깁니다. 여백이 부족하여 그림의 한계 근처에있는 굵은 선이 깎이지 않도록 이것을 수정했을 수도 있습니다.


답변

다음 bbox_inches="tight"에서 설정 하여 공백 패딩을 제거 할 수 있습니다 savefig.

plt.savefig("test.png",bbox_inches='tight')

당신은 인수를 bbox_inches문자열로 넣어야 할 것입니다. 아마도 이것이 당신을 위해 일찍 작동하지 않았기 때문일 것입니다.


가능한 중복 :

Matplotlib 플롯 : 축, 범례 및 공백 제거

matplotlib 그림의 여백을 설정하는 방법은 무엇입니까?

matplotlib 플롯에서 왼쪽 및 오른쪽 여백 감소


답변

성공하지 않고 위의 답변을 시도한 후 (그리고 다른 스택 게시물이 많았습니다) 마침내 나를 위해 일한 것은 단지

plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")

중요한 것은 bbox 또는 padding 인수를 포함하지 않습니다.


답변

Arvind Pereira ( http://robotics.usc.edu/~ampereir/wordpress/?p=626 ) 에서 무언가를 발견하고 나를 위해 일하는 것 같았습니다.

plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)


답변

다음 함수는 위의 johannes-s 답변을 통합합니다. 나는 그것을 테스트 한 plt.figureplt.subplots()다중 축으로, 그리고 그것을 잘 작동합니다.

def save(filepath, fig=None):
    '''Save the current image with no whitespace
    Example filepath: "myfig.png" or r"C:\myfig.pdf"
    '''
    import matplotlib.pyplot as plt
    if not fig:
        fig = plt.gcf()

    plt.subplots_adjust(0,0,1,1,0,0)
    for ax in fig.axes:
        ax.axis('off')
        ax.margins(0,0)
        ax.xaxis.set_major_locator(plt.NullLocator())
        ax.yaxis.set_major_locator(plt.NullLocator())
    fig.savefig(filepath, pad_inches = 0, bbox_inches='tight')


답변

다음 코드가 작업에 완벽하게 작동한다는 것을 알았습니다.

fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)


답변

나는이 순서를 따랐고 그것은 매력처럼 작동했습니다.

plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',
    bbox_inches='tight', pad_inches=0, format='pdf', dpi=1200)