简体   繁体   中英

edge detection opencv python

it is my code and I'm trying to edge detection using the sobel method. But I'm getting neither error nor image.If I have a mistake, can you explain where it is?

import cv2
import numpy as np

img=cv2.imread("lena.jpg")
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
m,n=img.shape


kernelx=np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
kernely=np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])


gx=np.zeros((m,n), dtype=np.int32)
gy=np.zeros((m,n), dtype=np.int32)


for x in range(1,m-1):
    for y in range(1,n-1):
        for a in range(3):
            for b in range(3):
                xn = x + a - 1
                yn = y + b - 1
                gx=gx+(kernelx[a][b]*img[xn][yn])
                gy=gy+(kernely[a][b]*img[xn][yn])






        final_image=np.sqrt(pow(gx,2.0)+pow(gy,2.0))



cv2.imshow("a",final_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

You have an error in your code.
Try to use cv2.filter2D() instead of your for loop.

import cv2
import numpy as np

img = cv2.imread(r"lena.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
m, n = img.shape

kernelx = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
kernely = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])

img_x = cv2.filter2D(img, ddepth=cv2.CV_8U, kernel=kernelx)
img_y = cv2.filter2D(img, ddepth=cv2.CV_8U, kernel=kernely)

final_image = np.sqrt(pow(img_x, 2.0) + pow(img_y, 2.0))

cv2.imshow("a", final_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

if you want to do it with a for loop, the right way of doing it is:
I add a tqdm progress bar for you;)

import cv2
import numpy as np
from tqdm import tqdm

img = cv2.imread(r"lena.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
m, n = img.shape

kernelx = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
kernely = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])

out_im = np.zeros((m-2, n-2))
g_x = np.zeros((m-2, n-2))
g_y = np.zeros((m-2, n-2))
for m_i in tqdm(range(m-2)):
    for n_i in range(n-2):
        im_patch = img[m_i:m_i+3, n_i:n_i+3]
        g_x[m_i, n_i] = sum([i * k for i, k in zip(im_patch.flatten(), kernelx.flatten())])
        g_y[m_i, n_i] = sum([i * k for i, k in zip(im_patch.flatten(), kernely.flatten())])

out_im = np.sqrt(g_x ** 2 + g_y ** 2)

out_im = np.uint8(out_im/out_im.max() * 255)

cv2.imshow("", out_im)
cv2.waitKey(0)
cv2.destroyAllWindows()

Note:

You may need to normalize the image before display.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM