Skip to content

Commit

Permalink
Merge pull request spmallick#277 from krutikabapat/master
Browse files Browse the repository at this point in the history
Added Hough Transform Code
  • Loading branch information
spmallick authored Mar 12, 2019
2 parents ec1d9dc + c2f0ad8 commit 3c484a6
Show file tree
Hide file tree
Showing 7 changed files with 295 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Hough-Transform/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## Hough Transform with OpenCV in C++ and Python

### Hough Line Transform

**Usage**

**Python**

- ```python3 hough_line.py road.png```

**C++**

- ```g++ hough_line.cpp `pkg-config opencv --cflags --libs` -o hough_line```
- ```./hough_line```

### Hough Circle Transform

**Usage**

**Python**

- ```python3 hough_circles.py circles.png```

**C++**

- ```g++ hough_circles.cpp `pkg-config opencv --cflags --libs` -o hough_circles```
- ```./hough_circles circles.png```
Binary file added Hough-Transform/circles.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
78 changes: 78 additions & 0 deletions Hough-Transform/hough_circles.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <iostream>
#include <string>


using namespace cv;
using namespace std;

// Declare variables to store images
Mat dst, gray_src, cdstP, src;

int thresh;
const int thresh_max = 100;
double t;

// Vector to store circle points
vector<Vec3f> circles;

void on_trackbar( int , void* ) {
cdstP = gray_src.clone();

// Apply hough transform
HoughCircles(cdstP, circles, HOUGH_GRADIENT, 1, cdstP.rows/64, 200, 10, 1, thresh);

cdstP = src.clone();

// Draw circle on points
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
circle( cdstP, center, radius, Scalar(255, 255, 255), 2, 8, 0 );
}

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);
imshow( "Output-Image", cdstP);
}


int main(int argc, char** argv){
const char* file = argv[1];
src = imread(file, IMREAD_COLOR);
cv::resize(src, src, cv::Size(400, 400));

if(src.empty())
{
cout << "Error reading image" << file<< endl;
return -1;
}

// Remove noise using medianBlur
medianBlur(src, src, 3);

// Convert to gray-scale
cvtColor(src, gray_src, COLOR_BGR2GRAY);

// Will hold the results of the detection
namedWindow("Output-Image", 1);

thresh = 10;

createTrackbar("threshold", "Output-Image", &thresh, thresh_max, on_trackbar);
on_trackbar(thresh, 0);

imshow("source", src);
while(true)
{
int c;
c = waitKey( 0 );
if( (char)c == 27 )
{ break; }
}

}
59 changes: 59 additions & 0 deletions Hough-Transform/hough_circles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import cv2
import numpy as np
import sys

def onTrackbarChange(max_slider):
cimg = np.copy(img)

# Detect circles using HoughCircles transform
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, cimg.shape[0]/64, param1=200, param2=10, minRadius=1, maxRadius=max_slider)

# If at least 1 circle is detected
if circles is not None:
cir_len = circles.shape[1] # store length of circles found
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
# draw the outer circle
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
else:
cir_len = 0 # no circles detected
# draw number of circles detected
cv2.putText(cimg, str(cir_len), (200, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 255), 4, cv2.LINE_AA)

cv2.imshow('Output-Image', cimg)

if __name__ == "__main__":
# Read image
img = cv2.imread(sys.argv[1], 1)

if(img is None):
print("Image not ready properly.")
print("Check your file path.")
sys.exit(0)

cv2.namedWindow("Output-Image")

# Resize image
img = cv2.resize(img, (400, 400))

# Convert to gray-scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Remove noise using median blur
gray_blur = cv2.medianBlur(gray, 3)

thresh = 10 # initial threshold value for trackbar
thresh_max = 100 # maximum value for the trackbar for hough transform

cv2.createTrackbar("threshold", "Output-Image", thresh, thresh_max, onTrackbarChange)
onTrackbarChange(thresh)

while True:
cv2.imshow("source image", img)
key = cv2.waitKey(1)
if key == ord('q'):
break

cv2.destroyAllWindows()
77 changes: 77 additions & 0 deletions Hough-Transform/hough_line.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <iostream>

using namespace cv;
using namespace std;

// variables to store images
Mat dst, cdstP, gray, src;

int thresh;
const int thresh_max = 100;
double t;

// create a vector to store points of line
vector<Vec4i> linesP;

void on_trackbar( int , void* )
{
cdstP = src.clone();

// apply hough line transform
HoughLinesP(dst, linesP, 1, CV_PI/180, thresh, 10, 250);

// draw lines on the detected points
for( size_t i = 0; i < linesP.size(); i++ )
{
Vec4i l = linesP[i];
line( cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255,0,0), 3, LINE_AA);
}

// show the resultant image
imshow("Result Image", cdstP);
}

int main(int argc, char** argv) {
const char* file = argv[1];
// Read image (color mode)
src = imread(file, 1);

if(src.empty())
{
cout << "Error in reading image" << file<< endl;
return -1;
}

// Convert to gray-scale
cvtColor(src, gray, COLOR_BGR2GRAY);

// Detect edges using Canny Edge Detector
Canny(gray, dst, 50, 200, 3);

// Make a copy of original image
cdstP = src.clone();

// Will hold the results of the detection
namedWindow("Result Image", 1);

// Declare thresh to vary the max_radius of circles to be detected in hough transform
thresh = 50;

// Create trackbar to change threshold values
createTrackbar("threshold", "Result Image", &thresh, thresh_max, on_trackbar);
on_trackbar(thresh, 0);

// Show the final image with trackbar
imshow("Source Image", src);
while(true)
{
int c;
c = waitKey( 20 );
if( (char)c == 27 )
{ break; }
}
}
54 changes: 54 additions & 0 deletions Hough-Transform/hough_line.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import cv2
import numpy as np
import sys

def onTrackbarChange(max_slider):
global img
global dst
global gray

dst = np.copy(img)
# Detect edges in the image
edges = cv2.Canny(gray, 50, 200)
# Apply hough line transform
lines = cv2.HoughLinesP(edges, 1, np.pi/180, max_slider, minLineLength=10, maxLineGap=250)

# Draw lines on the detected points
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(dst, (x1, y1), (x2, y2), (255,0,0), 3)

cv2.imshow("Result Image", dst)

if __name__ == "__main__":
if(len(sys.argv) > 1):
# Read image
img = cv2.imread(sys.argv[1], 1)
else:
print("Path not specified. Please specify image path")
sys.exit(0)

# Create a copy for later usage
dst = np.copy(img)

cv2.namedWindow("Result Image")

# Convert image to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Initialize thresh value
thresh = 80

# max_value of thresh
val = 100

cv2.createTrackbar("threshold", "Result Image", thresh, val, onTrackbarChange)
onTrackbarChange(val)

while True:
cv2.imshow("Source Image",img)
key = cv2.waitKey(1)
if key == ord('q'):
break

cv2.destroyAllWindows()
Binary file added Hough-Transform/road.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 3c484a6

Please sign in to comment.