OpenCV and Matplotlib show an image in differnt ways

Viewed 823

I am trying to plot an image after some processing. I get three different images using the three options below. The image obtained is after applying the Sobel filter twice on a road lane image.

sample_image.jpg The three methods to plot are shown in the below Python code.

    img = cv2.imread('sample_image.jpg')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    gaussian = cv2.GaussianBlur(gray,(3,3),0)

    sobely = cv2.Sobel(gaussian,cv2.CV_64F,1,0,ksize=5)  # y
    sobelyy = cv2.Sobel(sobely,cv2.CV_64F,1,0,ksize=5)  # y

    # method 1
    cv2.imshow('sobelyy', sobelyy) 

    # method 2
    cv2.imwrite('filtered_img1.JPG', sobelyy)
    s_img = cv2.imread('filtered_img1.JPG')
    cv2.imshow('s_img', s_img)

    # method 3
    plt.figure()
    plt.imshow(sobelyy, cmap='gray')
    plt.title('Filtered sobelyy image, B(x,y)'), plt.xticks([]), plt.yticks([])
    plt.show()

The images I get are:

method 1

method 2

method 3

The image I want to get is the one obtained in method 3.

Why are the images shown in different ways? How can I get to save the output image like the result of method 3?

Thank you in advance!

1 Answers

Why are the images shown in different ways?

OpenCV and Matplotlib use different color spaces to display images - that's why they look differently even when they are actually the same.

As for your first 2 methods those should actually look the same and they do when I try out your code.

How can I get to save the output image like the result of method 3?

Matplotlib has a build in function to write plotted images to disc, just use:

plt.savefig('your_filename.png')
Related