Home > Software engineering >  How to use Canny Edge Detection in OpenCV with keeping the colored image? Python
How to use Canny Edge Detection in OpenCV with keeping the colored image? Python

Time:11-08

So I am trying to outline a blue colored box with a white line using Canny Edge Detection. It's just a black background with a blue square in the middle of the screen. This is the code I currently have:

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

img = cv.imread('BlueSquare.png',0)
edges = cv.Canny(img,100,200)
plt.subplot(121),plt.imshow(img,cmap = 'Blues')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'bone')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

plt.show()

I want my code to show the original image next to the same image but outlined in white.

The code ends up giving me a different original image. It changes the background from black to a light blue and the blue square to a different blue. Also, the second outline image is just all black with no outline or any blue square. I know that CV is in BGR format and matplot is in RGB I was going to change the values after the fact I just want to get it working with the ouline first. Anyone know how I can fix this? Thank you in advance

CodePudding user response:

I have gone through the code, basically, you are loading the image in grayscale as you are passing '0', "img = cv.imread('BlueSquare.png',0)" with the image name which means now you don't have the original image so what I did is load the original image and then convert into the grayscale as the canny function takes a grayscale image as input. After that before passing the original image to plt.show(), I have converted it to RGB from BGR. Moreover, the canny image is being shown properly, let me attach my results.

import cv2 as cv
from matplotlib import pyplot as plt

img = cv.imread('Brand.jpeg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray,100,200)

im_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.subplot(121),plt.imshow(im_rgb,cmap = 'Blues')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'bone')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

plt.show()

Result

enter image description here

  • Related