Harris Обнаружение углов и Ши-Томаси Обнаружение углов — два популярных алгоритма, используемые для определения углов на изображениях. Эти углы важны, поскольку они часто соответствуют важным функциям, которые могут быть полезны в различных задачах компьютерного зрения, таких как сшивание изображений, отслеживание объектов и т. д.

В OpenCV вы можете использовать функцию cv2.cornerHarris для Обнаружения угла Харриса. Вот как вы можете их использовать:

import cv2
import numpy as np

# Load the image
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Convert image to float32
image = np.float32(image)

# Apply Harris corner detection
corner_response = cv2.cornerHarris(image, blockSize=2, ksize=3, k=0.04)

# Dilate the corner response to enhance corner points
corner_response = cv2.dilate(corner_response, None)

# Threshold for corner detection
threshold = 0.01 * corner_response.max()

# Create a copy of the image for marking the corners
marked_image = image.copy()

# Mark the detected corners
marked_image[corner_response > threshold] = [0, 0, 255]  # Red color for corners

# Display the result
cv2.imshow('Harris Corner Detection', marked_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Еще один простой код для обнаружения угла Харриса ::…..

"""
For understanding  this we recall jisaw puzzle game where we combine multiple 
small pieces in correct order by identifying its corners , shape and pattern.

On the basis of all these we all detect corners in images with so many approaches,
"""
# Corner here refers to point where straight line turn into some shapes.
# example a rectangle has four corners.

#Harris Corner Detection 

"""
OpenCV has the function cv2.cornerHarris() for this purpose. Its arguments are :

img - Input image, it should be grayscale and float32 type.
blockSize - It is the size of neighbourhood considered for corner detection
ksize - Aperture parameter of Sobel derivative used.
k - Harris detector free parameter in the equation.
"""
import numpy as np
import cv2 as cv

img = cv.imread('Data\\shapes.png')

cv.imshow('img', img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

gray = np.float32(gray)

res= cv.cornerHarris(gray, 2, 3, 0.04)

res = cv.dilate(res, None)

img[res > 0.01 * res.max()] = [0, 0, 255]  # marked color

cv.imshow('dst', img)

if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()

Выход:….

И функция cv2.goodFeaturesToTrack для Обнаружения угла Ши-Томаси. Вот как вы можете их использовать:

import cv2
import numpy as np

# Load the image
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Detect Shi-Tomasi corners
corners = cv2.goodFeaturesToTrack(image, maxCorners=100, qualityLevel=0.01, minDistance=10)

# Convert corners to integers
corners = np.int0(corners)

# Create a copy of the image for marking the corners
marked_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)

# Mark the detected corners
for corner in corners:
    x, y = corner.ravel()
    cv2.circle(marked_image, (x, y), 3, (0, 0, 255), -1)  # Red color for corners

# Display the result
cv2.imshow('Shi-Tomasi Corner Detection', marked_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Еще один фрагмент кода с простым кодом для обнаружения углов Ши-Томаси.

#Shi- Tomasi approach is more effective as compared with Harris Corner detection

#In this we limit the number of corners and corners quality.
#It is more user friendly.

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

img = cv2.imread('Data\\shapes.png')
#image must be in gary
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#parameters (img,no.of corner,quality_level,min_distance between corner)
corners = cv2.goodFeaturesToTrack(gray,10,0.01,20)
corners = np.int64(corners)

for i in corners:
    x,y = i.ravel()
    cv2.circle(img,(x,y),3,255,-1)

cv2.imshow("res==",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
"""

Выход:…..

Не забудьте заменить 'image.jpg' фактическим путем к файлу изображения. Оба эти метода выделяют обнаруженные углы на изображении красными кружками. Выбор между использованием Harris или Shi-Tomasi зависит от вашего конкретного применения и требований. Ши-Томази обычно считается более надежным и точным для обнаружения углов.