Skip to content
This repository was archived by the owner on Nov 30, 2022. It is now read-only.

Commit e0627bb

Browse files
authored
Merge pull request #247 from simarpreetsingh-019/master
Detecting geometrical shapes using opencv
2 parents 29f72b0 + 6590e85 commit e0627bb

15 files changed

+317
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import cv2
2+
import numpy as np
3+
4+
from matplotlib import pyplot as plt
5+
6+
img = cv2.imread("messi5.jpg", cv2.IMREAD_GRAYSCALE )
7+
lap = cv2.Laplacian(img, cv2.CV_64F, ksize = 1)
8+
lap = np.uint8(np.absolute(lap))
9+
sobelX = cv2.Sobel(img, cv2.CV_64F, 1, 0)
10+
sobelY = cv2.Sobel(img, cv2.CV_64F, 0, 1)
11+
canny = cv2.Canny(img, 100, 200)
12+
13+
sobelX = np.uint8(np.absolute(sobelX))
14+
sobelY = np.uint8(np.absolute(sobelY))
15+
16+
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
17+
18+
titles = ['images','Laplacian', 'SobelX', 'SobelY', 'sobelCombined', 'Canny']
19+
images = [img, lap, sobelX, sobelY, sobelCombined, canny]
20+
21+
for i in range(6):
22+
plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')
23+
plt.title(titles[i])
24+
plt.xticks([]), plt.yticks([])
25+
26+
plt.show()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
from scipy import ndimage
2+
from scipy.ndimage.filters import convolve
3+
4+
from scipy import misc
5+
import numpy as np
6+
7+
8+
class cannyEdgeDetector:
9+
def __init__(self, imgs, sigma=1, kernel_size=5, weak_pixel=75, strong_pixel=255, lowthreshold=0.05,
10+
highthreshold=0.15):
11+
self.imgs = imgs
12+
self.imgs_final = []
13+
self.img_smoothed = None
14+
self.gradientMat = None
15+
self.thetaMat = None
16+
self.nonMaxImg = None
17+
self.thresholdImg = None
18+
self.weak_pixel = weak_pixel
19+
self.strong_pixel = strong_pixel
20+
self.sigma = sigma
21+
self.kernel_size = kernel_size
22+
self.lowThreshold = lowthreshold
23+
self.highThreshold = highthreshold
24+
return
25+
26+
def gaussian_kernel(self, size, sigma=1):
27+
size = int(size) // 2
28+
x, y = np.mgrid[-size:size + 1, -size:size + 1]
29+
normal = 1 / (2.0 * np.pi * sigma ** 2)
30+
g = np.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2))) * normal
31+
return g
32+
33+
def sobel_filters(self, img):
34+
Kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32)
35+
Ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.float32)
36+
37+
Ix = ndimage.filters.convolve(img, Kx)
38+
Iy = ndimage.filters.convolve(img, Ky)
39+
40+
G = np.hypot(Ix, Iy)
41+
G = G / G.max() * 255
42+
theta = np.arctan2(Iy, Ix)
43+
return (G, theta)
44+
45+
def non_max_suppression(self, img, D):
46+
M, N = img.shape
47+
Z = np.zeros((M, N), dtype=np.int32)
48+
angle = D * 180. / np.pi
49+
angle[angle < 0] += 180
50+
51+
for i in range(1, M - 1):
52+
for j in range(1, N - 1):
53+
try:
54+
q = 255
55+
r = 255
56+
57+
# angle 0
58+
if (0 <= angle[i, j] < 22.5) or (157.5 <= angle[i, j] <= 180):
59+
q = img[i, j + 1]
60+
r = img[i, j - 1]
61+
# angle 45
62+
elif (22.5 <= angle[i, j] < 67.5):
63+
q = img[i + 1, j - 1]
64+
r = img[i - 1, j + 1]
65+
# angle 90
66+
elif (67.5 <= angle[i, j] < 112.5):
67+
q = img[i + 1, j]
68+
r = img[i - 1, j]
69+
# angle 135
70+
elif (112.5 <= angle[i, j] < 157.5):
71+
q = img[i - 1, j - 1]
72+
r = img[i + 1, j + 1]
73+
74+
if (img[i, j] >= q) and (img[i, j] >= r):
75+
Z[i, j] = img[i, j]
76+
else:
77+
Z[i, j] = 0
78+
79+
80+
except IndexError as e:
81+
pass
82+
83+
return Z
84+
85+
def threshold(self, img):
86+
87+
highThreshold = img.max() * self.highThreshold;
88+
lowThreshold = highThreshold * self.lowThreshold;
89+
90+
M, N = img.shape
91+
res = np.zeros((M, N), dtype=np.int32)
92+
93+
weak = np.int32(self.weak_pixel)
94+
strong = np.int32(self.strong_pixel)
95+
96+
strong_i, strong_j = np.where(img >= highThreshold)
97+
zeros_i, zeros_j = np.where(img < lowThreshold)
98+
99+
weak_i, weak_j = np.where((img <= highThreshold) & (img >= lowThreshold))
100+
101+
res[strong_i, strong_j] = strong
102+
res[weak_i, weak_j] = weak
103+
104+
return (res)
105+
106+
def hysteresis(self, img):
107+
108+
M, N = img.shape
109+
weak = self.weak_pixel
110+
strong = self.strong_pixel
111+
112+
for i in range(1, M - 1):
113+
for j in range(1, N - 1):
114+
if (img[i, j] == weak):
115+
try:
116+
if ((img[i + 1, j - 1] == strong) or (img[i + 1, j] == strong) or (img[i + 1, j + 1] == strong)
117+
or (img[i, j - 1] == strong) or (img[i, j + 1] == strong)
118+
or (img[i - 1, j - 1] == strong) or (img[i - 1, j] == strong) or (
119+
img[i - 1, j + 1] == strong)):
120+
img[i, j] = strong
121+
else:
122+
img[i, j] = 0
123+
except IndexError as e:
124+
pass
125+
126+
return img
127+
128+
def detect(self):
129+
imgs_final = []
130+
for i, img in enumerate(self.imgs):
131+
self.img_smoothed = convolve(img, self.gaussian_kernel(self.kernel_size, self.sigma))
132+
self.gradientMat, self.thetaMat = self.sobel_filters(self.img_smoothed)
133+
self.nonMaxImg = self.non_max_suppression(self.gradientMat, self.thetaMat)
134+
self.thresholdImg = self.threshold(self.nonMaxImg)
135+
img_final = self.hysteresis(self.thresholdImg)
136+
self.imgs_final.append(img_final)
137+
138+
return self.imgs_final
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
[![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com)
2+
3+
# Canny Edge detection using OpenCV and python
4+
5+
<div align="center">
6+
<img src="https://miro.medium.com/max/700/0*eZT8V5qNeSiXiXBn.png" height=500 width="1000">
7+
</div>
8+
9+
## What is Canny Edge Detection?
10+
11+
> It is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images.
12+
It was developed by John F. Canny ,an Australian computer scientist, back in 1986.
13+
14+
15+
16+
### _The Canny edge detection algorithm is composed of 5 steps_:
17+
+ Noise reduction;
18+
+ Gradient calculation;
19+
+ Non-maximum suppression;
20+
+ Double threshold;
21+
+ Edge Tracking by Hysteresis.
22+
23+
## Lets see how it's done.
24+
25+
<div align="center">
26+
<img src="Images/pic1.JPG" >
27+
</div>
28+
29+
1. ### Input image:
30+
Input in RGB format.
31+
<div align="center">
32+
<img src="Images/input image.JPG" width="400">
33+
</div>
34+
35+
2. ### Converting the image to grayscale:
36+
For easier calculations.
37+
<div align="center">
38+
<img src="Images/tograyscale.JPG" width="400">
39+
</div>
40+
41+
42+
3. ### Smoothing the image:
43+
Smoothing of image for noise reduction. Gradient is the first order derivatives of image for each direction.
44+
It is cause of edges that seems more and the edges look thick.
45+
<div align="center">
46+
<img src="Images/res1pic1.JPG" width="400">
47+
</div>
48+
49+
4. ### Image gradient:
50+
Gradient is the function of the partial derivatives. I applied to the image convolution process with Sobel filters to obtain this partial derivative.
51+
<div align="center">
52+
<img src="Images/res3sudoku.JPG" width="400">
53+
</div>
54+
55+
5. ### Non-maximum suppression:
56+
In this step the pixel is compared with its two neighbors of the pixel, if the compared pixel is larger than neighbor we do not change the pixel,
57+
otherwise, this pixel is not maximum value hence, we set the zero to that pixel.
58+
59+
6. ### Tracking the edge by hysteresis:
60+
In this step we choose two type of threshold, high and low threshold value. Afterward, each pixel of image is compared with two different threshold value.
61+
If the pixel is larger than the high threshold, this pixel mark with 255 in the final image.
62+
If the pixel between high threshold and low threshold. If the pixel is smaller than low-threshold image, mark as black with 0 (black) value in the resulting image.
63+
64+
7. ### Final Results:
65+
After passing all of the mentioned steps, we will give the final result from the method.
66+
67+
# Output Results:
68+
69+
<div align="center">
70+
<img src="Images/glimpse all result.JPG" >
71+
</div>
72+
73+
74+
## Endnote:
75+
### **For more detail on learning Canny Edge Detection and maths behind, see my article** [here](https://medium.com/simply-dev/what-is-canny-edge-detection-cfefa272a8d0)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
[![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com)
2+
## Detecting Geometrical shapes in an image using OpenCV
3+
### What is Contours?
4+
5+
Contours can be explained simply as a curve joining all the continuous points (along the boundary), having the same color or intensity.
6+
The contours are a useful tool for shape analysis and object detection and recognition.
7+
8+
### Why we discussing about contours?
9+
We will be using Contours to first find the curving of object, then will be checkin and naming about shape of it depending on sides of object.
10+
11+
## Approach :
12+
The approach we would use to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has.
13+
For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle, and so on.
14+
15+
### Important :
16+
Please add the image you want to use this on in the same folder you are saving the code, or else add the whole location.
17+
18+
## Language used : Python
19+
20+
21+
## Libraries used:
22+
1. OpenCV
23+
2. Numpy
24+
25+
26+
### Input
27+
28+
<div align="center">
29+
<img src="https://github.com/simarpreetsingh-019/Awesome-Python-Scripts/blob/master/Image-Processing/Detecting%20Contours/shapes.png" width="250">
30+
</div>
31+
32+
33+
### output
34+
35+
<div align="center">
36+
<img src="https://github.com/simarpreetsingh-019/Awesome-Python-Scripts/blob/master/Image-Processing/Detecting%20Contours/output2.JPG" width="250">
37+
</div>
38+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import numpy as np
2+
import cv2
3+
4+
img = cv2.imread('shapes.PNG')
5+
imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
6+
7+
ret , thrash = cv2.threshold(imgGry, 240 , 255, cv2.CHAIN_APPROX_NONE)
8+
contours , hierarchy = cv2.findContours(thrash, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
9+
10+
for contour in contours:
11+
approx = cv2.approxPolyDP(contour, 0.01* cv2.arcLength(contour, True), True)
12+
cv2.drawContours(img, [approx], 0, (0, 0, 0), 5)
13+
x = approx.ravel()[0]
14+
y = approx.ravel()[1] - 5
15+
16+
if len(approx) == 3:
17+
cv2.putText( img, "Triangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0) )
18+
elif len(approx) == 4 :
19+
x, y , w, h = cv2.boundingRect(approx)
20+
aspectRatio = float(w)/h
21+
print(aspectRatio)
22+
23+
if aspectRatio >= 0.95 and aspectRatio < 1.05:
24+
cv2.putText(img, "square", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
25+
26+
else:
27+
cv2.putText(img, "rectangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
28+
29+
elif len(approx) == 5 :
30+
cv2.putText(img, "pentagon", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
31+
32+
elif len(approx) == 10 :
33+
cv2.putText(img, "star", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
34+
35+
else:
36+
cv2.putText(img, "circle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
37+
38+
cv2.imshow('shapes', img)
39+
cv2.waitKey(0)
40+
cv2.destroyAllWindows()
24.2 KB
Loading
3.92 KB
Loading

0 commit comments

Comments
 (0)