Invert colors when plotting a PNG file using matplotlib

后端 未结 4 1934
-上瘾入骨i
-上瘾入骨i 2021-01-12 19:33

I\'m trying to display a PNG file using matplotlib and of course, python. For this test, I\'ve generated the following image:

相关标签:
4条回答
  • 2021-01-12 20:19

    Color image loaded by OpenCV is in BGR mode. However, Matplotlib displays in RGB mode. So we need to convert the image from BGR to RGB:

    plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))
    
    0 讨论(0)
  • 2021-01-12 20:23

    Try:

    plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))
    
    0 讨论(0)
  • 2021-01-12 20:27

    As others have pointed out, the problem is that numpy arrays are in BGR format, but matplotlib expects the arrays to be ordered in a different way.

    You are looking for scipy.misc.toimage:

    import scipy.misc
    rgb = scipy.misc.toimage(cube)
    

    Alternatively, you can use scipy.misc.imshow().

    0 讨论(0)
  • 2021-01-12 20:30

    It appears that you may somehow have RGB switched with BGR. Notice that your greens are retained but all the blues turned to red. If cube has shape (M,N,3), try swapping cube[:,:,0] with cube[:,:,2]. You can do that with numpy like so:

    rgb = numpy.fliplr(cube.reshape(-1,3)).reshape(cube.shape)
    

    From the OpenCV documentation:

    Note: In the case of color images, the decoded images will have the channels stored in B G R order.

    0 讨论(0)
提交回复
热议问题