3 OpenCV source codes of edge calculation using Sobel filter are shown here. 2 is correct, and 1 is wrong.
If you search websites, you will find 3 types of implementation shown here for Sobel filter's OpenCV sample source code. Web is always full with fakes. You have to judge whether the web contents are true or not by your own brain. Do not always rely on the website's source code. You have to fully understand about Sobel filter and OpenCV to judge correctly.
Any source code are the same. Any information are the same. Web is always full with wrong information. Knowledge, ability, and judgment are necessary to find the correct information from the web.
from google.colab import files
import os
import numpy as np
import cv2
def main():
if os.path.exists('circle.png'):
os.remove('circle.png')
files.upload()
img = cv2.imread('circle.png', cv2.IMREAD_COLOR)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dx = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=3)
dy = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=3)
output = np.sqrt(dx ** 2 + dy ** 2)
cv2.imwrite('result1.png', output)
files.download('result1.png')
if __name__ == '__main__':
main()
from google.colab import files
import os
import cv2
def main():
if os.path.exists('circle.png'):
os.remove('circle.png')
files.upload()
img = cv2.imread('circle.png', cv2.IMREAD_COLOR)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
output = cv2.Sobel(img_gray, cv2.CV_64F, 1, 1, ksize=3)
cv2.imwrite('result2.png', output)
files.download('result2.png')
if __name__ == '__main__':
main()
from google.colab import files
import os
import numpy as np
import cv2
def main():
if os.path.exists('circle.png'):
os.remove('circle.png')
files.upload()
image = cv2.imread('circle.png', cv2.IMREAD_COLOR)
input = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
input = np.float64(input)
input = input / 255
filterx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
filtery = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]
output = input.copy()
row, col = output.shape
for y in range(0, row):
for x in range(0, col):
dx = 0
dy = 0
for i in range(0,
3):
for j in range(0, 3):
yy = y + i - 1
xx = x + j - 1
if xx >= 0 and yy >= 0 and xx < col and yy
< row:
val = input[yy, xx]
dx += val * filterx[i][j]
dy += val * filtery[i][j]
output[y, x] =
np.sqrt(dx ** 2 + dy ** 2)
cv2.imwrite('result3.png', output * 255)
files.download('result3.png')
if __name__ == '__main__':
main()