Python cv2.HoughLinesP() Examples
The following are 19
code examples of cv2.HoughLinesP().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cv2
, or try the search function
.
Example #1
Source File: RealWorld.py From Monocular-Obstacle-Avoidance with BSD 2-Clause "Simplified" License | 6 votes |
def sim_noise(self, depthFile, rgbFile): img=depthFile imgcol=rgbFile edges = cv2.Canny(img,100,200,apertureSize = 3) edgescol = cv2.Canny(imgcol,100,200,apertureSize = 3) edges += edgescol mask=img.copy() mask.fill(0) minLineLength = 10 maxLineGap = 10 lines = cv2.HoughLinesP(edges,1,np.pi/180,20,100,10) if lines is not None: for line in lines: for x1,y1,x2,y2 in line: cv2.line(mask,(x1,y1),(x2,y2),255,1) for i in range(480): for j in range(640): if mask[i][j]>0: cv2.circle(img,(j,i),2, (0,0,0), -1) if random.random()>0.8: cv2.circle(img,(j,i), random.randint(2,6), (0,0,0), -1) return img
Example #2
Source File: hough_rotate.py From namsel with MIT License | 5 votes |
def get_avg_angle(a, draw=False): lines = cv.HoughLinesP(a, 1, np.pi/180, 1, minLineLength=a.shape[1]*.30, maxLineGap=50) angles = [] if lines is not None: for line in lines[0]: if draw: cv.line(a, tuple(line[0:2]), tuple(line[2:]), 1, thickness=2) angle = np.arctan2(line[3]-line[1], line[2]-line[0]) angles.append(angle) return np.mean(angles)*degree_scaler else: return 0
Example #3
Source File: transboundary.py From WorkControl with Apache License 2.0 | 5 votes |
def line_detect_possible_demo(image): global img # 提取图片中黄色区域(hsv空间) lower_blue = np.array([26, 43, 46]) upper_blue = np.array([34, 255, 255]) frame = image # cv2.imshow('Capture', frame) # change to hsv model hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # get mask mask = cv2.inRange(hsv, lower_blue, upper_blue) # detect red res = cv2.bitwise_and(frame, frame, mask=mask) ret, binary = cv2.threshold(res, 200, 255, cv2.THRESH_BINARY) kernel = np.ones((5, 5), np.uint8) # 图像进行膨胀处理 dilation = cv2.dilate(binary, kernel) # 图像腐蚀处理 erosion = cv2.erode(dilation, kernel) erosion = cv2.cvtColor(erosion, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(erosion, 100, 150, apertureSize=3) #edges = cv2.Canny(binary, 50, 150, apertureSize=3) # apertureSize是sobel算子大小,只能为1,3,5,7 # cv2.imshow('1',edges) # cv2.waitKey(0) lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=0,maxLineGap=10) #函数将通过步长为1的半径和步长为π/180的角来搜索所有可能的直线 list= [] for i in range(len(lines)): x1 = lines[i][0][0] y1 = lines[i][0][1] x2 = lines[i][0][2] y2 = lines[i][0][3] list.append((x1,y1,x2,y2)) cv2.line(image,(x1,y1),(x2,y2),(0,0,255),2) return list
Example #4
Source File: mainDetect.py From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International | 5 votes |
def houghLines(self, edges, image, debug=True): """ Detects Hough lines """ # Detect hough lines lines = cv2.HoughLinesP(edges, rho=1, theta=1 * np.pi / 180, threshold=40, minLineLength=100, maxLineGap=50) N = lines.shape[0] # Draw lines on image New = [] for i in range(N): x1 = lines[i][0][0] y1 = lines[i][0][1] x2 = lines[i][0][2] y2 = lines[i][0][3] New.append([x1,y1,x2,y2]) lines = [Line(x1=New[i][0],y1= New[i][1], x2= New[i][2], y2=New[i][3]) for i in range(len(New))] # Categorise the lines into horizontal or vertical horizontal, vertical = self.categoriseLines(lines) # Filter out close lines based to achieve 9 # STANDARD THRESHOLD SHOULD BE 20 ver = filterClose(vertical, horizontal=False, threshold=20) hor = filterClose(horizontal, horizontal=True, threshold=20) #print(len(ver)) #print(len(hor)) # DEBUG TO SHOW LINES if debug: debugImg = image.copy() self.drawLines(debugImg, ver) self.drawLines(debugImg, hor) #cv2.imshow("2 Hough Lines Found", debugImg) cv2.imwrite("2HoughLinesFound.jpeg", debugImg) return hor, ver
Example #5
Source File: pogoWindows.py From Map-A-Droid with GNU General Public License v3.0 | 5 votes |
def __checkRaidLine(self, filename, hash, leftSide=False, clickinvers=False): log.debug("__checkRaidLine: Reading lines") if leftSide: log.debug("__checkRaidLine: Check nearby open ") try: screenshotRead = cv2.imread(filename) except: log.error("Screenshot corrupted :(") return False if screenshotRead is None: log.error("Screenshot corrupted :(") return False if self.__readCircleCount(os.path.join('', filename), hash, float(11), xcord=False, crop=True, click=False, canny=True) == -1: log.debug("__checkRaidLine: Not active") return False height, width, _ = screenshotRead.shape screenshotRead = screenshotRead[int(height / 2) - int(height / 3):int(height / 2) + int(height / 3), int(0):int(width)] gray = cv2.cvtColor(screenshotRead, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) log.debug("__checkRaidLine: Determined screenshot scale: " + str(height) + " x " + str(width)) edges = cv2.Canny(gray, 50, 150, apertureSize=3) maxLineLength = width / 3.30 + width * 0.03 log.debug("__checkRaidLine: MaxLineLength:" + str(maxLineLength)) minLineLength = width / 6.35 - width * 0.03 log.debug("__checkRaidLine: MinLineLength:" + str(minLineLength)) maxLineGap = 50 lines = cv2.HoughLinesP(edges, rho = 1, theta = math.pi / 180, threshold = 70, minLineLength = minLineLength, maxLineGap = 2) if lines is None: return False for line in lines: for x1, y1, x2, y2 in line: if not leftSide: if y1 == y2 and (x2 - x1 <= maxLineLength) and ( x2 - x1 >= minLineLength) and x1 > width / 2 and x2 > width / 2 and y1 < (height / 2): log.debug("__checkRaidLine: Raid-tab is active - Line lenght: " + str( x2 - x1) + "px Coords - X: " + str(x1) + " " + str(x2) + " Y: " + str(y1) + " " + str(y2)) return True # else: log.debug("__checkRaidLine: Raid-tab is not active - Line lenght: " + str(x2-x1) + "px # Coords - X: " + str(x1) + " " + str(x2) + " Y: " + str(y1) + " " + str(y2)) return False else: if y1 == y2 and (x2 - x1 <= maxLineLength) and ( x2 - x1 >= minLineLength) and ((x1 < width / 2 and x2 < width / 2) or (x1 < width / 2 and x2 > width / 2)) and y1 < (height / 2): log.debug("__checkRaidLine: Nearby is active - but not Raid-Tab") if clickinvers: xRaidTab = int(width - (x2-x1)) yRaidTab = int((int(height / 2) - int(height / 3)+y1) * 0.9) log.debug('__checkRaidLine: open Raid-Tab' ) self.screenWrapper.click(xRaidTab, yRaidTab) time.sleep(3) return True # else: # log.debug("__checkRaidLine: Nearby not active - but maybe Raid-tab") # return False log.debug("__checkRaidLine: Not active") return False
Example #6
Source File: lane_detector.py From ncappzoo with MIT License | 5 votes |
def hough_lines(image): """ Creates hough line Note that: `image` should be the output of a Canny transform. :param image: |Image| camera frame :return: hough lines (not the image with lines) """ return cv2.HoughLinesP(image, 2, np.pi / 180, 50, maxLineGap=50)
Example #7
Source File: SuironCV.py From suiron with MIT License | 5 votes |
def get_lane_lines(inframe): frame = inframe.copy() ret_frame = np.zeros(frame.shape, np.uint8) # We converted it into RGB when we normalized it gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) gray = get_median_blur(gray) canny = get_canny(gray) # Hough lines # threshold = number of 'votes' before hough algorithm considers it a line lines = cv2.HoughLinesP(canny, 1, np.pi/180, threshold=25, minLineLength=40, maxLineGap=100) try: r = lines.shape[0] except AttributeError: r = 0 for i in range(0): for x1, y1, x2, y2 in lines[i]: # Degrees as its easier for me to conceptualize angle = math.atan2(y1-y2, x1-x2)*180/np.pi # If it looks like a left or right lane # Draw it onto the new image if 100 < angle < 170 or -170 < angle < -100: cv2.line(ret_frame, (x1, y1), (x2, y2), (255, 255, 255), 10) return ret_frame
Example #8
Source File: page_elements2.py From namsel with MIT License | 5 votes |
def draw_hough_outline(self, arr): arr = invert_bw(arr) # import Image # Image.fromarray(arr*255).show() # h = cv.HoughLinesP(arr, 2, np.pi/4, 5, minLineLength=arr.shape[0]*.10) h = cv.HoughLinesP(arr, 2, np.pi/4, 1, minLineLength=arr.shape[0]*.15, maxLineGap=5) #This # h = cv.HoughLinesP(arr, 2, np.pi/4, 1, minLineLength=arr.shape[0]*.15, maxLineGap=1) # h = cv.HoughLinesP(arr, 2, np.pi/4, 1, minLineLength=arr.shape[0]*.15) PI_O4 = np.pi/4 # if h and h.any(): # if self._page_type == 'pecha': # color = 1 # thickness = 10 # else: # Attempt to erase horizontal lines if page_type == book. # # Why? Horizontal lines can break LineCluster if they are broken # # e.g. couldn't be filtered out prior to line_breaker.py # color = 0 # thickness = 10 if h is not None: for line in h[0]: new = (line[2]-line[0], line[3] - line[1]) val = (new[0]/np.sqrt(np.dot(new, new))) theta = np.arccos(val) if theta >= PI_O4: # Vertical line # print line[1] - line[3] # cv.line(arr, (line[0], 0), (line[0], arr.shape[0]), 1, thickness=10) if line[0] < .5*arr.shape[1]: arr[:,:line[0]+12] = 0 else: arr[:,line[0]-12:] = 0 else: # horizontal line if line[2] - line[0] >= .15 * arr.shape[1]: # cv.line(arr, (0, line[1]), (arr.shape[1], line[1]), 1, thickness=50) if line[1] < .5 *arr.shape[0]: arr[:line[1]+17, :] = 0 else: arr[line[1]-5:,:] = 0 return ((arr*-1)+1).astype(np.uint8)
Example #9
Source File: solver.py From airport with Apache License 2.0 | 5 votes |
def FindInternalBox(bw): """Finds where the puzzle card is located. Detects all vertical and horizontal lines, and returns the largest contour that bounds them""" # Invert colors. HoughLines searches white lines on black background target = 255 - bw.copy() DebugShow(target) lines = cv2.HoughLinesP(target, 1, np.pi / 180, 100, 100, 10) if lines is None: logging.debug("HoughLinesP failed") return None logging.debug("Found {} lines using HoughLinesP".format(len(lines))) lines_image = np.zeros_like(target) for line in lines: for x1, y1, x2, y2 in line: if abs(x1 - x2) < 20: # vertical line x = min(x1, x2) cv2.line(lines_image, (x, y1), (x, y2), 255, 0) if abs(y1 - y2) < 20: y = min(y1, y2) cv2.line(lines_image, (x1, y), (x2, y), 255, 0) kernel = np.ones((5, 5), np.uint8) lines_image = cv2.dilate(lines_image, kernel, iterations=2) DebugShow(lines_image) return FindExternalContour(lines_image)
Example #10
Source File: main.py From Traffic-Sign-Detection with MIT License | 5 votes |
def remove_line(img): gray = img.copy() edges = cv2.Canny(gray,50,150,apertureSize = 3) minLineLength = 5 maxLineGap = 3 lines = cv2.HoughLinesP(edges,1,np.pi/180,15,minLineLength,maxLineGap) mask = np.ones(img.shape[:2], dtype="uint8") * 255 if lines is not None: for line in lines: for x1,y1,x2,y2 in line: cv2.line(mask,(x1,y1),(x2,y2),(0,0,0),2) return cv2.bitwise_and(img, img, mask=mask)
Example #11
Source File: part-7-self-driving-example.py From pygta5 with GNU General Public License v3.0 | 5 votes |
def process_img(image): original_image = image # edge detection processed_img = cv2.Canny(image, threshold1 = 200, threshold2=300) processed_img = cv2.GaussianBlur(processed_img,(5,5),0) vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500], ], np.int32) processed_img = roi(processed_img, [vertices]) # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html # rho theta thresh min length, max gap: lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15) m1 = 0 m2 = 0 try: l1, l2, m1,m2 = draw_lanes(original_image,lines) cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30) cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30) except Exception as e: print(str(e)) pass try: for coords in lines: coords = coords[0] try: cv2.line(processed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 3) except Exception as e: print(str(e)) except Exception as e: pass return processed_img,original_image, m1, m2
Example #12
Source File: part-5-line-finding.py From pygta5 with GNU General Public License v3.0 | 5 votes |
def process_img(original_image): processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300) processed_img = cv2.GaussianBlur(processed_img, (3,3), 0 ) vertices = np.array([[10,500],[10,300], [300,200], [500,200], [800,300], [800,500]], np.int32) processed_img = roi(processed_img, [vertices]) # edges lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15) draw_lines(processed_img,lines) return processed_img
Example #13
Source File: main.py From pygta5 with GNU General Public License v3.0 | 5 votes |
def process_img(image): original_image = image # convert to gray processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # edge detection processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300) processed_img = cv2.GaussianBlur(processed_img,(5,5),0) vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500], ], np.int32) processed_img = roi(processed_img, [vertices]) # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html # rho theta thresh min length, max gap: lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15) m1 = 0 m2 = 0 try: l1, l2, m1,m2 = draw_lanes(original_image,lines) cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30) cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30) except Exception as e: print(str(e)) pass try: for coords in lines: coords = coords[0] try: cv2.line(processed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 3) except Exception as e: print(str(e)) except Exception as e: pass return processed_img,original_image, m1, m2
Example #14
Source File: part-6-lane-finder.py From pygta5 with GNU General Public License v3.0 | 5 votes |
def process_img(image): original_image = image # convert to gray processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # edge detection processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300) processed_img = cv2.GaussianBlur(processed_img,(5,5),0) vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500], ], np.int32) processed_img = roi(processed_img, [vertices]) # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html # rho theta thresh min length, max gap: lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15) try: l1, l2 = draw_lanes(original_image,lines) cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30) cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30) except Exception as e: print(str(e)) pass try: for coords in lines: coords = coords[0] try: cv2.line(processed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 3) except Exception as e: print(str(e)) except Exception as e: pass return processed_img,original_image
Example #15
Source File: line_detect_1.py From crop_row_detection with GNU General Public License v3.0 | 5 votes |
def crop_point_hough(crop_points): height = len(crop_points) width = len(crop_points[0]) #crop_line_data = cv2.HoughLinesP(crop_points, 1, math.pi/180, 2, 10, 10) crop_line_data = cv2.HoughLines(crop_points, HOUGH_RHO, HOUGH_ANGLE, HOUGH_THRESH) crop_lines = np.zeros((height, width, 3), dtype=np.uint8) if crop_line_data != None: crop_line_data = crop_line_data[0] #print(crop_line_data) if len(crop_line_data[0]) == 2: for [rho, theta] in crop_line_data: #print(rho, theta) if (theta <= ANGLE_THRESH) or (theta >= math.pi-ANGLE_THRESH): a = math.cos(theta) b = math.sin(theta) x0 = a*rho y0 = b*rho point1 = (int(round(x0+1000*(-b))), int(round(y0+1000*(a)))) point2 = (int(round(x0-1000*(-b))), int(round(y0-1000*(a)))) cv2.line(crop_lines, point1, point2, (0, 0, 255), 2) elif len(crop_line_data[0]) == 4: for [x0, y0, x1, y1] in crop_line_data: cv2.line(crop_lines, (x0, y0), (x1, y1), (0, 0, 255), 2) else: print("No lines found") return crop_lines
Example #16
Source File: 检测线条和形状-几何形状.py From OpenCV-Python-Tutorial with MIT License | 5 votes |
def lines(self): lines = cv2.HoughLinesP(self.image, 1, np.pi / 2, 6, None, 50, 10) for line in lines[0]: pt1 = (line[0], line[1]) pt2 = (line[2], line[3]) cv2.line(self.image, pt1, pt2, (0, 0, 255), 2)
Example #17
Source File: object_finder.py From baxter_demos with Apache License 2.0 | 4 votes |
def getObjectAxes(self, img, contour): # Get the bounding rectangle around the detected object rect = cv2.boundingRect(contour) # Calculate a border around the bounding rectangle pad = int((rect[2]+rect[3])*params['pad']) if rect[0] < pad: x = 0 else: x = rect[0]-pad if rect[1] < pad: y = 0 else: y = rect[1]-pad p1 = (x, y) x, y = rect[0]+rect[2]+pad, rect[1]+rect[3]+pad if x > img.shape[1]: x = img.shape[1] - 1 if y > img.shape[0]: y = img.shape[0] - 1 p2 = (x, y) cv2.rectangle(self.cur_img, p2, p1, (0, 255, 0), 3) # Extract the region of interest around the detected object subimg = img[p1[1]:p2[1], p1[0]:p2[0]] # Hough line detection lines = cv2.HoughLinesP(subimg, *self.houghArgs) if lines is None: rospy.loginfo( "no lines found" ) return None lines = lines.reshape(lines.shape[1], lines.shape[2]) # Calculate the lengths of each line lengths = numpy.square(lines[:, 0]-lines[:, 2]) +\ numpy.square(lines[:, 1]-lines[:, 3]) lines = numpy.hstack((lines, lengths.reshape((lengths.shape[0], 1)) )) lines = lines[lines[:,4].argsort()] lines = lines[::-1] #Reverse the sorted array lines = lines[:, 0:4] bestline = lines[0] #Get the longest line bestline += numpy.tile(numpy.array(p1), 2) axis = numpy.hstack( (bestline[0:2], 0, bestline[2:4], 0) ) print "axis found:", axis return axis
Example #18
Source File: bot.py From siPintar with MIT License | 4 votes |
def processImage(image): # Loading test images # image = cv2.imread('test_images/solidWhiteRight.jpg') # Convert to Grey Image grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Define a kernel size and apply Gaussian smoothing kernel_size = 5 blur_gray = cv2.GaussianBlur(grey_image, (kernel_size, kernel_size), 0) # Define our parameters for Canny and apply low_threshold = 50 high_threshold = 150 edges = cv2.Canny(blur_gray, low_threshold, high_threshold) # Next we'll create a masked edges image using cv2.fillPoly() mask = np.zeros_like(edges) ignore_mask_color = 255 # Defining Region of Interest imshape = image.shape vertices = np.array([[(0, imshape[0]), (450, 320), (500, 320), (imshape[1], imshape[0])]], dtype=np.int32) cv2.fillPoly(mask, vertices, ignore_mask_color) masked_edges = cv2.bitwise_and(edges, mask) # Define the Hough transform parameters # Make a blank the same size as our image to draw on rho = 2 # distance resolution in pixels of the Hough grid theta = np.pi / 180 # angular resolution in radians of the Hough grid threshold = 15 # minimum number of votes (intersections in Hough grid cell) min_line_length = 40 # minimum number of pixels making up a line max_line_gap = 30 # maximum gap in pixels between connectable line segments line_image = np.copy(image) * 0 # creating a blank to draw lines on # Run Hough on edge detected image # Output "lines" is an array containing endpoints of detected line segments lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap) # Iterate over the output "lines" and draw lines on a blank image for line in lines: for x1, y1, x2, y2 in line: cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 10) # Create a "color" binary image to combine with line image # color_edges = np.dstack((edges, edges, edges)) # Draw the lines on the original image lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0) return lines_edges
Example #19
Source File: platesOCR.py From LicensePlates-OCR with MIT License | 4 votes |
def cleanOCR(borders): detectedOCR = [] for i, image in enumerate(borders): image = cv2.imread(image) edges = cv2.Canny(image, 50, 150, apertureSize=3) lines = cv2.HoughLinesP(image=edges, rho=1, theta=np.pi / 180, threshold=100, lines=np.array([]), minLineLength=100, maxLineGap=80) a, b, c = lines.shape for i in range(a): x = lines[i][0][0] - lines[i][0][2] y = lines[i][0][1] - lines[i][0][3] if x != 0: if abs(y / x) < 1: cv2.line(image, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 255, 255), 1, cv2.LINE_AA) se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)) gray = cv2.morphologyEx(image, cv2.MORPH_CLOSE, se) # OCR config = '-l eng --oem 1 --psm 3' text = pytesseract.image_to_string(gray, config=config) validChars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] cleanText = [] for char in text: if char in validChars: cleanText.append(char) plate = ''.join(cleanText) # print(plate) detectedOCR.append(plate) # cv2.imshow('img', gray) # cv2.waitKey(0) return detectedOCR