Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mstfldmr/45d6e47bb661800b982c39d30215bc88 to your computer and use it in GitHub Desktop.
Save mstfldmr/45d6e47bb661800b982c39d30215bc88 to your computer and use it in GitHub Desktop.
from matplotlib import pyplot as plt
import cv2
img = cv2.imread('/Users/mustafa/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
plt.title('my picture')
plt.show()
@aspenstarss
Copy link

@Rage-ops
Great! It's work for me.

@Abhuthahir
Copy link

What should we do if we get: "AttributeError: module 'cv2.cv2' has no attribute 'COLOR_BGR2RBG'"
image

@volkov-maxim
Copy link

What should we do if we get: "AttributeError: module 'cv2.cv2' has no attribute 'COLOR_BGR2RBG'"

Try COLOR_BGR2RGB (RGB, not RBG).

@delarco
Copy link

delarco commented Aug 16, 2021

We can also use display() of IPython.display module and Image.fromarray() of PIL module

from PIL import Image
import cv2 
from IPython.display import display

img = cv2.imread('image.png') # with the OpenCV function imread(), the order of colors is BGR (blue, green, red).

# In Pillow, the order of colors is assumed to be RGB (red, green, blue).
# As we are using Image.fromarray() of PIL module, we need to convert BGR to RGB.

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Converting BGR to RGB

display(Image.fromarray(img))

Worked really nice! Thank you so much!

@r0oland
Copy link

r0oland commented Nov 16, 2022

Here is a simple function based on the code above to display the image with an optional title.

def show_rgb_image(image, title=None, conversion=cv2.COLOR_BGR2RGB):

    # Converts from one colour space to the other. this is needed as RGB
    # is not the default colour space for OpenCV
    image = cv2.cvtColor(image, conversion)

    # Show the image
    plt.imshow(image)

    # remove the axis / ticks for a clean looking image
    plt.xticks([])
    plt.yticks([])

    # if a title is provided, show it
    if title is not None:
        plt.title(title)

    plt.show()

Usage is simple:

image = cv2.imread(r'c:\Users\johan\Pictures\road.jpg')
show_rgb_image(image, 'Original Image')

image

@AliNiaz990487
Copy link

One more example for displaying a color image. Matplot lib expects img in RGB format but OpenCV provides it in BGR.

RGB_im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)

Screenshot from 2024-06-08 12-44-04
Screenshot from 2024-06-08 12-44-26

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment