0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Haar-like特徴量を用いた直線検出

Last updated at Posted at 2022-05-24

Pythonを使って直線検出をする

環境

・Ubuntu18.04
・Python3

import numpy as np
import cv2
import itertools


def calc_haarlike(crop_img):
    crop_img = crop_img[:,::-1]

    threshold = 10
    rect_w = 8
    pattern_w = rect_w // 2 
    width = crop_img.shape[1]
    
    peak_index = 0
    max_value = 0
    
    for index in range(width-rect_w):
        a1 = np.mean(crop_img[:, index: index+pattern_w])
        a2 = np.mean(crop_img[:, index+pattern_w: index+rect_w])
        H = a1-a2 
        if max_value < H and H - max_value > threshold:
            max_value = H
            peak_index = index

    index = width - peak_index + rect_w
    return index if max_value > 0 else -1

def candidate_extraction(img):
    n = []
    h, w = img.shape[0], img.shape[1]
    wh = 8 #window height
    window_pos = np.array([
        [[400, 600], [500, 700]],
        [[380, 580], [520, 720]],
        [[360, 560], [540, 740]],
        
        [[700, 900], [800, 1000]],
        [[680, 880], [820, 1020]],
        [[660, 860], [840, 1040]],
    ])

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    for i, ((x1, y1), (x2, y2)) in enumerate(window_pos):
        crop_img = gray[y1: y2, x1: x2]
        peak_index = calc_haarlike(crop_img)
        cv2.imwrite("./img_gray_"+str(i)+".jpg", crop_img)
        cv2.line(img,pt1=(x1, y1), pt2=(x2,y2),color=(0,0,255),thickness=10)
        if peak_index != -1:
            cv2.circle(img, (x1+peak_index, y1), 5, (255, 0, 0), thickness=1)
            n.append([x1 + peak_index,y1])

    t = itertools.combinations(n,2)
    for i in t:
        print(i)
        a,b = linear(i[0],i[1])
        if a != 0:
            cv2.line(img,pt1=(0,b), pt2=(int((len(img) - b)/a),len(img)),color=(0,255,0),thickness=10)
            cv2.line(img,pt1=(0,b), pt2=(len(img[0]),int(len(img[0])*a + b)),color=(0,255,0),thickness=10)
        else:
            cv2.line(img,pt1=(0, int(b)), pt2=(len(img[0]),int(b)),color=(0,255,0),thickness=10)
    cv2.imwrite("./img.jpg", img)

def linear(n1, n2):
    a = (n2[1]-n1[1])/(n2[0]-n1[0])
    b = int((n2[0]*n1[1]-n1[0]*n2[1])/(n2[0]-n1[0]))
    return a, b

def main():
    img = cv2.imread("./data/path.jpg")
    candidate_extraction(img)

if __name__ == '__main__':
    main()

参考

こちらの方のプログラムを参考にしております。

https://nsr-9.hatenablog.jp/entry/2021/08/15/120000

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?