2016-12-13 2 views
3

저는 OpenCV과 함께 새롭습니다. 내 첫 번째 작은 스크립트를 만들기 위해 일부 자습서와 설명서를 읽고 있습니다.OpenCV Python을 사용하여 개체 검색

나는 이미지를 가지고 있고이 일에 detect objects 원하는 : 가로등, 쓰레기통 ... 같은

내 이미지가 보이는 :이 스크립트를 작성

enter image description here

:

import cv2 

img_filt = cv2.medianBlur(cv2.imread('ville.jpg',0), 5) 
img_th = cv2.adaptiveThreshold(img_filt,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) 
img_filt, contours, hierarchy = cv2.findContours(img_th, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) 

display = cv2.imshow("Objects",img_filt) 
wait_time = cv2.waitKey(0) 

그러나 사각형으로 그림 결과를 어떻게 표시 할 수 있습니까?

정말 고마워요!

+0

와 브 루트 포스 매칭 내가 추천입니다 그러나? 명확하게하십시오 – nithin

+0

템플릿 일치를 사용하여 동일한 크기 및 방향의 객체를 감지 할 수 있습니다. 여기는 [링크] (http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html#template-matching)입니다 –

+0

@nithin 그래, 처음으로 미안 해요. OpenCV를 사용하고 있습니다. 목표는 가로등, 쓰레기통, .. 사진을 감지하는 것입니다. 나는 그것을하기에 아주 좋은 튜토리얼을 실제로 찾지 못한다. –

답변

1

내가 개인적으로 사용하고 권장하는 SIFT (Scale-Invariant Feature Transform) 또는 SURF 알고리즘을 사용하는 것이지만이 알고리즘은 OpenCV 3에 포함되어 있지 않으며 , openCV2에서 여전히 availble, 이것에 대한 좋은 대안으로 ORB를 사용하는 것을 선호한다. 이것은 SIFT/SURF의 opensource implementationaition이다. SIFT 기술자와

브 루트 포스 매칭 및 비율 테스트는 여기

우리는 최고의 경기 케이 얻을 BFMatcher.knnMatch()를 사용합니다. 이 예제에서 우리는 그의 논문에서 D.Lowe가 설명한 비율 테스트를 적용 할 수 있도록 k = 2를 취할 것입니다.SIFT와 플란넬을 사용하여 플란넬 기반 Matcher를

FLANN stands for Fast Library for Approximate Nearest Neighbors. It contains a collection of algorithms optimized for fast nearest neighbor search in large datasets and for high dimensional features. It works more faster than BFMatcher for large datasets. We will see the second example with FLANN based matcher.

For FLANN based matcher, we need to pass two dictionaries which specifies the algorithm to be used, its related parameters etc. First one is IndexParams. For various algorithms, the information to be passed is explained in FLANN docs. As a summary, for algorithms like SIFT, SURF etc.

샘플 코드와 함께 앞으로 이동

An sample output for above code would be

import numpy as np 
import cv2 
from matplotlib import pyplot as plt 

img1 = cv2.imread('box.png',0)   # queryImage 
img2 = cv2.imread('box_in_scene.png',0) # trainImage 

# Initiate SIFT detector 
sift = cv2.SIFT() 

# find the keypoints and descriptors with SIFT 
kp1, des1 = sift.detectAndCompute(img1,None) 
kp2, des2 = sift.detectAndCompute(img2,None) 

# BFMatcher with default params 
bf = cv2.BFMatcher() 
matches = bf.knnMatch(des1,des2, k=2) 

# Apply ratio test 
good = [] 
for m,n in matches: 
    if m.distance < 0.75*n.distance: 
     good.append([m]) 

# cv2.drawMatchesKnn expects list of lists as matches. 
img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,flags=2) 

plt.imshow(img3),plt.show() 
:

:

import numpy as np 
import cv2 
from matplotlib import pyplot as plt 

img1 = cv2.imread('box.png',0)   # queryImage 
img2 = cv2.imread('box_in_scene.png',0) # trainImage 

# Initiate SIFT detector 
sift = cv2.SIFT() 

# find the keypoints and descriptors with SIFT 
kp1, des1 = sift.detectAndCompute(img1,None) 
kp2, des2 = sift.detectAndCompute(img2,None) 

# FLANN parameters 
FLANN_INDEX_KDTREE = 0 
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) 
search_params = dict(checks=50) # or pass empty dictionary 

flann = cv2.FlannBasedMatcher(index_params,search_params) 

matches = flann.knnMatch(des1,des2,k=2) 

# Need to draw only good matches, so create a mask 
matchesMask = [[0,0] for i in xrange(len(matches))] 

# ratio test as per Lowe's paper 
for i,(m,n) in enumerate(matches): 
    if m.distance < 0.7*n.distance: 
     matchesMask[i]=[1,0] 

draw_params = dict(matchColor = (0,255,0), 
        singlePointColor = (255,0,0), 
        matchesMask = matchesMask, 
        flags = 0) 

img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,**draw_params) 



plt.imshow(img3,),plt.show() 

아래의 결과를 참조 617,451,515,

enter image description here

는, ORB의 기술자를 감지 원하는 작업 객체

In this example I used ORB with Bruteforce matcher, this code captures frames from camera at realtime and computes the keypoints,descriptors from input frames and compares it with the stored query image, by doing the same , and returns the matching keypoint lengths, the same can be applied on above code which uses SIFT algorithm instead of ORB.

import numpy as np 
import cv2 
from imutils.video import WebcamVideoStream 
from imutils.video import FPS 

MIN_MATCH_COUNT = 10 

img1 = cv2.imread('input_query.jpg', 0) 


orb = cv2.ORB() 
kp1, des1 = orb.detectAndCompute(img1, None) 

webcam = WebcamVideoStream(src=0).start() 
fps = FPS().start() 

while True: 
    img2 = webcam.read() 
    key = cv2.waitKey(10) 
    cv2.imshow('',img2) 
    if key == 1048603: 
     break 
    kp2, des2 = orb.detectAndCompute(img2, None) 

    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) 

    matches = bf.match(des1, des2) 
    matches = sorted(matches, key=lambda x: x.distance) # compute the descriptors with ORB 

    if not len(matches) > MIN_MATCH_COUNT: 
     print "Not enough matches are found - %d/%d" % (len(matches), MIN_MATCH_COUNT) 
     matchesMask = None 

    #simg2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA) 

    print len(matches) 
    #img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2) 

    fps.update() 

fps.stop() 

More descriptive video tutorial on this will be found here, https://www.youtube.com/watch?v=ZW3nrP2OyLQ and one more good thing is it's opensource : https://gitlab.com/josemariasoladuran/object-recognition-opencv-python.git

+0

매우 긴 대답에 감사드립니다. 제가 이런 종류의 librairies를 가지고있어서 정말 힘들어요. –

+0

내 대답은, 나는 주어진 입력 이미지/프레임에서 가장 좋은 neraly mathichg 키포인트를 찾고 우리가 비교하고 싶은 이미지와 비교하고, 단순히 우리가 이미 가지고있는 어떤 객체를 찾는다. 입력 img와 저장된 img를 비교합니다. 따라서이 경우에는 최대 수만 필요합니다. 주어진 i/p 이미지에서 찾을 수있는 우리가 알고있는 수학 키포인트 (keypoints). –

+0

이 비디오를 확인하십시오 : https://www.youtube.com/watch?v=ZW3nrP2OyLQ 오픈 소스이므로, 여기에서 복제하십시오, git clone https://gitlab.com/josemariasoladuran/object-recognition-opencv- python.git, opencv3에서 이것을 실행하도록하십시오. 이것이 정확히 당신이 찾고있는 것입니다! –

0

답변으로 코드를 게시했지만 필터로 검색 한 등고선 만 표시합니다. 이 유형의 필터는 이미지가 B & W이고 슈퍼 콤플렉스가 아닌 경우 컨투어 검색에 좋습니다. 그렇지 않으면 당신이 무엇을 찾고 있는지 생각할 것입니다. 그리고 약간의 필터가 필요합니다.

처음에 요청한 것이기 때문에 matplotlib 디스플레이도 추가했으나 할 수있는 것처럼 유용하지는 않습니다.

import cv2 
import matplotlib.pyplot as plt 

img_orig = cv2.imread('ville.jpg',0) 
img_filt = cv2.medianBlur(img_orig, 5) 
img_th = cv2.adaptiveThreshold(img_filt,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) 
contours, hierarchy = cv2.findContours(img_th, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) 

plt.imshow(img_orig) 

cv2.drawContours(img_orig,contours,-1,(128,255,0),1) 
display = cv2.imshow("Objects",img_orig) 
wait_time = cv2.waitKey(0) 
cv2.destroyAllWindows() 

추가 유용한 링크 : http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html

나중에 편집 당신은 당신이 여기에서 찾을 수있는 고급 물체 감지 시작 얻을 수있는 몇 가지 유용한 문학 : http://www.cs.utoronto.ca/~fidler/teaching/2015/CSC2523.html

참고 :이 의미에 더 의미 물체 감지 및 모양을 묘사하는 단순한 윤곽선 감지가 아닙니다.

+0

나는 당신 스크립트가 꽤 잘 이해하고있다. 나는 몇 가지 수정을 시도했지만이 오류가 발생했습니다 :'Traceback (최근 호출 마지막) : 파일 "image.py", 줄 17, contours, hierarchy = cv2.findContours (img_th, cv2.RETR_LIST, cv2 .CHAIN_APPROX_SIMPLE) ValueError : 압축을 풀 값이 너무 많습니다. –

+0

어떤 버전의 Python을 사용하고 있습니까? 귀하의 초기 예제에서와 같이 3 개의 인수로 호출 해보십시오. 예 :'Python 2.7에서'image, contours, hierarchy = cv2 ...'나는'contours, hierarchy = cv2.findContours()'의 두 인자를 가진'cv2.findContours' 만 사용할 수 있습니다. – Roxanne

+0

@Andro이 오류를 극복하기 위해 이것을 사용하십시오 'contours, hierarchy = cv2.findContours (thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) [- 2 :]' –

관련 문제