Skip to content

Commit 3c484a6

Browse files
authored
Merge pull request spmallick#277 from krutikabapat/master
Added Hough Transform Code
2 parents ec1d9dc + c2f0ad8 commit 3c484a6

File tree

7 files changed

+295
-0
lines changed

7 files changed

+295
-0
lines changed

Hough-Transform/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
## Hough Transform with OpenCV in C++ and Python
2+
3+
### Hough Line Transform
4+
5+
**Usage**
6+
7+
**Python**
8+
9+
- ```python3 hough_line.py road.png```
10+
11+
**C++**
12+
13+
- ```g++ hough_line.cpp `pkg-config opencv --cflags --libs` -o hough_line```
14+
- ```./hough_line```
15+
16+
### Hough Circle Transform
17+
18+
**Usage**
19+
20+
**Python**
21+
22+
- ```python3 hough_circles.py circles.png```
23+
24+
**C++**
25+
26+
- ```g++ hough_circles.cpp `pkg-config opencv --cflags --libs` -o hough_circles```
27+
- ```./hough_circles circles.png```

Hough-Transform/circles.png

108 KB
Loading

Hough-Transform/hough_circles.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include <opencv2/core/core.hpp>
2+
#include <opencv2/highgui/highgui.hpp>
3+
#include <opencv2/video/background_segm.hpp>
4+
#include <opencv2/opencv.hpp>
5+
#include <stdio.h>
6+
#include <iostream>
7+
#include <string>
8+
9+
10+
using namespace cv;
11+
using namespace std;
12+
13+
// Declare variables to store images
14+
Mat dst, gray_src, cdstP, src;
15+
16+
int thresh;
17+
const int thresh_max = 100;
18+
double t;
19+
20+
// Vector to store circle points
21+
vector<Vec3f> circles;
22+
23+
void on_trackbar( int , void* ) {
24+
cdstP = gray_src.clone();
25+
26+
// Apply hough transform
27+
HoughCircles(cdstP, circles, HOUGH_GRADIENT, 1, cdstP.rows/64, 200, 10, 1, thresh);
28+
29+
cdstP = src.clone();
30+
31+
// Draw circle on points
32+
for( size_t i = 0; i < circles.size(); i++ )
33+
{
34+
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
35+
int radius = cvRound(circles[i][2]);
36+
circle( cdstP, center, radius, Scalar(255, 255, 255), 2, 8, 0 );
37+
}
38+
39+
cv::putText(cdstP, to_string(circles.size()), cv::Point(280, 60), cv::FONT_HERSHEY_SIMPLEX, 2, cv::Scalar(255, 0, 255), 4, cv::LINE_AA);
40+
imshow( "Output-Image", cdstP);
41+
}
42+
43+
44+
int main(int argc, char** argv){
45+
const char* file = argv[1];
46+
src = imread(file, IMREAD_COLOR);
47+
cv::resize(src, src, cv::Size(400, 400));
48+
49+
if(src.empty())
50+
{
51+
cout << "Error reading image" << file<< endl;
52+
return -1;
53+
}
54+
55+
// Remove noise using medianBlur
56+
medianBlur(src, src, 3);
57+
58+
// Convert to gray-scale
59+
cvtColor(src, gray_src, COLOR_BGR2GRAY);
60+
61+
// Will hold the results of the detection
62+
namedWindow("Output-Image", 1);
63+
64+
thresh = 10;
65+
66+
createTrackbar("threshold", "Output-Image", &thresh, thresh_max, on_trackbar);
67+
on_trackbar(thresh, 0);
68+
69+
imshow("source", src);
70+
while(true)
71+
{
72+
int c;
73+
c = waitKey( 0 );
74+
if( (char)c == 27 )
75+
{ break; }
76+
}
77+
78+
}

Hough-Transform/hough_circles.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import cv2
2+
import numpy as np
3+
import sys
4+
5+
def onTrackbarChange(max_slider):
6+
cimg = np.copy(img)
7+
8+
# Detect circles using HoughCircles transform
9+
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, cimg.shape[0]/64, param1=200, param2=10, minRadius=1, maxRadius=max_slider)
10+
11+
# If at least 1 circle is detected
12+
if circles is not None:
13+
cir_len = circles.shape[1] # store length of circles found
14+
circles = np.uint16(np.around(circles))
15+
for i in circles[0, :]:
16+
# draw the outer circle
17+
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
18+
# draw the center of the circle
19+
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
20+
else:
21+
cir_len = 0 # no circles detected
22+
# draw number of circles detected
23+
cv2.putText(cimg, str(cir_len), (200, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 255), 4, cv2.LINE_AA)
24+
25+
cv2.imshow('Output-Image', cimg)
26+
27+
if __name__ == "__main__":
28+
# Read image
29+
img = cv2.imread(sys.argv[1], 1)
30+
31+
if(img is None):
32+
print("Image not ready properly.")
33+
print("Check your file path.")
34+
sys.exit(0)
35+
36+
cv2.namedWindow("Output-Image")
37+
38+
# Resize image
39+
img = cv2.resize(img, (400, 400))
40+
41+
# Convert to gray-scale
42+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
43+
44+
# Remove noise using median blur
45+
gray_blur = cv2.medianBlur(gray, 3)
46+
47+
thresh = 10 # initial threshold value for trackbar
48+
thresh_max = 100 # maximum value for the trackbar for hough transform
49+
50+
cv2.createTrackbar("threshold", "Output-Image", thresh, thresh_max, onTrackbarChange)
51+
onTrackbarChange(thresh)
52+
53+
while True:
54+
cv2.imshow("source image", img)
55+
key = cv2.waitKey(1)
56+
if key == ord('q'):
57+
break
58+
59+
cv2.destroyAllWindows()

Hough-Transform/hough_line.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include <opencv2/core/core.hpp>
2+
#include <opencv2/highgui/highgui.hpp>
3+
#include <opencv2/opencv.hpp>
4+
#include <stdio.h>
5+
#include <iostream>
6+
7+
using namespace cv;
8+
using namespace std;
9+
10+
// variables to store images
11+
Mat dst, cdstP, gray, src;
12+
13+
int thresh;
14+
const int thresh_max = 100;
15+
double t;
16+
17+
// create a vector to store points of line
18+
vector<Vec4i> linesP;
19+
20+
void on_trackbar( int , void* )
21+
{
22+
cdstP = src.clone();
23+
24+
// apply hough line transform
25+
HoughLinesP(dst, linesP, 1, CV_PI/180, thresh, 10, 250);
26+
27+
// draw lines on the detected points
28+
for( size_t i = 0; i < linesP.size(); i++ )
29+
{
30+
Vec4i l = linesP[i];
31+
line( cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255,0,0), 3, LINE_AA);
32+
}
33+
34+
// show the resultant image
35+
imshow("Result Image", cdstP);
36+
}
37+
38+
int main(int argc, char** argv) {
39+
const char* file = argv[1];
40+
// Read image (color mode)
41+
src = imread(file, 1);
42+
43+
if(src.empty())
44+
{
45+
cout << "Error in reading image" << file<< endl;
46+
return -1;
47+
}
48+
49+
// Convert to gray-scale
50+
cvtColor(src, gray, COLOR_BGR2GRAY);
51+
52+
// Detect edges using Canny Edge Detector
53+
Canny(gray, dst, 50, 200, 3);
54+
55+
// Make a copy of original image
56+
cdstP = src.clone();
57+
58+
// Will hold the results of the detection
59+
namedWindow("Result Image", 1);
60+
61+
// Declare thresh to vary the max_radius of circles to be detected in hough transform
62+
thresh = 50;
63+
64+
// Create trackbar to change threshold values
65+
createTrackbar("threshold", "Result Image", &thresh, thresh_max, on_trackbar);
66+
on_trackbar(thresh, 0);
67+
68+
// Show the final image with trackbar
69+
imshow("Source Image", src);
70+
while(true)
71+
{
72+
int c;
73+
c = waitKey( 20 );
74+
if( (char)c == 27 )
75+
{ break; }
76+
}
77+
}

Hough-Transform/hough_line.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import cv2
2+
import numpy as np
3+
import sys
4+
5+
def onTrackbarChange(max_slider):
6+
global img
7+
global dst
8+
global gray
9+
10+
dst = np.copy(img)
11+
# Detect edges in the image
12+
edges = cv2.Canny(gray, 50, 200)
13+
# Apply hough line transform
14+
lines = cv2.HoughLinesP(edges, 1, np.pi/180, max_slider, minLineLength=10, maxLineGap=250)
15+
16+
# Draw lines on the detected points
17+
for line in lines:
18+
x1, y1, x2, y2 = line[0]
19+
cv2.line(dst, (x1, y1), (x2, y2), (255,0,0), 3)
20+
21+
cv2.imshow("Result Image", dst)
22+
23+
if __name__ == "__main__":
24+
if(len(sys.argv) > 1):
25+
# Read image
26+
img = cv2.imread(sys.argv[1], 1)
27+
else:
28+
print("Path not specified. Please specify image path")
29+
sys.exit(0)
30+
31+
# Create a copy for later usage
32+
dst = np.copy(img)
33+
34+
cv2.namedWindow("Result Image")
35+
36+
# Convert image to gray
37+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
38+
39+
# Initialize thresh value
40+
thresh = 80
41+
42+
# max_value of thresh
43+
val = 100
44+
45+
cv2.createTrackbar("threshold", "Result Image", thresh, val, onTrackbarChange)
46+
onTrackbarChange(val)
47+
48+
while True:
49+
cv2.imshow("Source Image",img)
50+
key = cv2.waitKey(1)
51+
if key == ord('q'):
52+
break
53+
54+
cv2.destroyAllWindows()

Hough-Transform/road.png

3.04 KB
Loading

0 commit comments

Comments
 (0)