반응형

Only two matching methods currently accept a mask: CV_TM_SQDIFF and CV_TM_CCORR_NORMED


The mask should have a CV_8U or CV_32F depth and the same number of channels and size as the target image. In CV_8U case, the mask values are treated as binary, i.e. zero and non-zero. In CV_32F case, the values should fall into [0..1] range and the target image pixels will be multiplied by the corresponding mask pixel values.


OpenCV matchTemplate 함수에 마스크를 적용해서 (배경이 다른) 같은 이미지를 모두 찾을 수 있다. 마스크는 CV_8U 아니면 CV_32F의 깊이값을 가져야 하며 target image와 같은 채널 수와 사이즈를 가져야 한다.


2019/07/08 - [Software/OpenCV] - Template Matching(Image Searching) - 부분 이미지 검색

2019/07/10 - [Software/OpenCV] - Template Matching(Image Searching) for multiple objects - 반복되는 이미지 모두 찾기


<Target>


<Mask>


<Source>


There are 3 objects(bones) to find in the source image.

Each of them has a different background as below.


Below code explains how to spot different background multiple objects with a mask.

Adjust threshold value if it doesn't work properly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <opencv2/opencv.hpp>
#include <time.h>
 
using namespace cv;
using namespace std;
 
int main()
{
    clock_t start, end;
    double minVal;
    Point minLoc;
    double threshold = 0.001;
    int count = 0;
 
    Mat FinalImage = imread("source.png", IMREAD_COLOR);
    if (FinalImage.empty())
        return -1;
 
    // Grayscale source, target and mask for faster calculation.
    Mat SourceImage;
    cvtColor(FinalImage, SourceImage, CV_BGR2GRAY);
 
    Mat TargetImage = imread("target.png", IMREAD_GRAYSCALE);
    if (TargetImage.empty())
        return -1;
 
    Mat Mask = imread("mask.png", IMREAD_GRAYSCALE);
    if (Mask.empty())
        return -1;
 
    Mat Result;
 
    start = clock();
    // Mask must have the same datatype and size with target image.
    // It is not set by default. Currently, only the TM_SQDIFF and TM_CCORR_NORMED methods are supported.
    matchTemplate(SourceImage, TargetImage, Result, TM_SQDIFF, Mask); // Type of the template matching operation: TM_SQDIFF
    normalize(Result, Result, 01, NORM_MINMAX, -1, Mat());
    minMaxLoc(Result, &minVal, NULL&minLoc, NULL);
 
    for (int i = 0; i < Result.rows; i++)
        for (int j = 0; j < Result.cols; j++)
            if (Result.at<float>(i, j) < threshold)
            {
                rectangle(FinalImage, Point(j, i), Point(j + TargetImage.cols, i + TargetImage.rows), Scalar(00255), 1);
                count++;
            }
    end = clock();
 
    cout << "Searching time: " << difftime(end, start) / CLOCKS_PER_SEC << endl;
    cout << "Minimum Value: " << minVal << " " << minLoc << endl;
    cout << "Threshold: " << threshold << endl;
    cout << "Found: " << count << endl;
 
    imshow("Mask", Mask);
    imshow("TargetImage", TargetImage);
    imshow("Result", Result);
    imshow("FinalImage", FinalImage);
 
    waitKey(0);
 
    return 0;
}
cs




Grayscale target image


Binary mask


Result image


Final image


Found 3 bones in 0.097 secs.



반응형
Posted by J-sean
:
반응형

Template matching is a technique for finding areas of an image that match (are similar) to a template image (patch).


OpenCV matchTemplate 함수와 threshold 값을 이용해 이미지에서 찾고 싶은 부분을 검색해 모두 찾을 수 있다.


2019/07/08 - [Software/OpenCV] - Template Matching(Image Searching) - 부분 이미지 검색

2019/07/12 - [Software/OpenCV] - Template Matching(Image Searching) with a mask for multiple objects - 마스크를 이용해 (배경이 다른) 반복되는 이미지 모두 찾기


<Target>


<Source>


Below code explains how to spot multiple objects with a threshold. Adjust threshold value if it doesn't work properly.

  • Type of the template matching operation: TM_SQDIFF_NORMED

  • Threshold: 0.00015

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <opencv2/opencv.hpp>
#include <time.h>
 
using namespace cv;
using namespace std;
 
int main()
{
    clock_t start, end;
    double minVal;
    Point minLoc;
    double threshold = 0.00015;
    int count = 0;
 
    Mat FinalImage = imread("source.jpg", IMREAD_COLOR);
    if (FinalImage.empty())
        return -1;
 
    // Grayscale source and target for faster calculation.
    Mat SourceImage;
    cvtColor(FinalImage, SourceImage, CV_BGR2GRAY);
 
    Mat TargetImage = imread("target.jpg", IMREAD_GRAYSCALE);
    if (TargetImage.empty())
        return -1;
 
    Mat Result;
 
    start = clock();
    matchTemplate(SourceImage, TargetImage, Result, TM_SQDIFF_NORMED); // Type of the template matching operation: TM_SQDIFF_NORMED
    minMaxLoc(Result, &minVal, NULL&minLoc, NULL);
 
    for (int i = 0; i < Result.rows; i++)
        for (int j = 0; j < Result.cols; j++)
            if (Result.at<float>(i, j) < threshold)
            {
                rectangle(FinalImage, Point(j, i), Point(j + TargetImage.cols, i + TargetImage.rows), Scalar(00255), 1);
                count++;
            }
    end = clock();
 
    cout << "Searching time: " << difftime(end, start) / CLOCKS_PER_SEC << endl;
    cout << "Minimum Value: " << minVal << " " << minLoc << endl;
    cout << "Threshold: " << threshold << endl;
    cout << "Found: " << count << endl;
 
    imshow("TargetImage", TargetImage);
    imshow("Result", Result);
    imshow("FinalImage", FinalImage);
 
    waitKey(0);
 
    return 0;
}
cs




<Result>


Found 4 coins in 0.035 secs.




반응형
Posted by J-sean
:
반응형

Template matching is a technique for finding areas of an image that match (are similar) to a template image (patch).


Python Pillow library로 구현해 봤던 Image searching 기술을 OpenCV matchTemplate 함수로 간단히 만들 수 있다.


2018/11/30 - [Software/Python] - Pillow 이미지 서치(Image Search) 1

2018/12/02 - [Software/Python] - Pillow 이미지 서치(Image Search) 2

2019/07/10 - [Software/OpenCV] - Template Matching(Image Searching) for multiple objects - 반복되는 이미지 모두 찾기

2019/07/12 - [Software/OpenCV] - Template Matching(Image Searching) with a mask for multiple objects - 마스크를 이용해 (배경이 다른) 반복되는 이미지 모두 찾기


<Target>


<Source>




Type of the template matching operation: TM_SQDIFF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <opencv2/opencv.hpp>
#include <time.h>
 
using namespace cv;
using namespace std;
 
int main()
{
    clock_t start, end;
    double minVal;
    Point minLoc;
 
    Mat FinalImage = imread("source.jpg", IMREAD_COLOR);
    if (FinalImage.empty())
        return -1;
 
    // Grayscale source and target for faster calculation.
    Mat SourceImage;
    cvtColor(FinalImage, SourceImage, CV_BGR2GRAY);
 
    Mat TargetImage = imread("target.jpg", IMREAD_GRAYSCALE);
    if (TargetImage.empty())
        return -1;
 
    Mat Result;
 
    start = clock();
    matchTemplate(SourceImage, TargetImage, Result, TM_SQDIFF); // Type of the template matching operation: TM_SQDIFF
    normalize(Result, Result, 01, NORM_MINMAX, -1, Mat());
    minMaxLoc(Result, &minVal, NULL&minLoc, NULL);
    end = clock();
 
    cout << "Searching time: " << difftime(end, start) / CLOCKS_PER_SEC << endl;
    cout << "Minimum Value: " << minVal << endl << "Location: " << minLoc << endl;
    rectangle(FinalImage, minLoc, Point(minLoc.x + TargetImage.cols, minLoc.y + TargetImage.rows), Scalar(00255), 1);
 
    imshow("TargetImage", TargetImage);
    imshow("Result", Result);
    imshow("FinalImage", FinalImage);
 
    waitKey(0);
 
    return 0;
}
cs


<Result>


Found the target at the husky's front paw in 0.014 secs.



반응형
Posted by J-sean
:
반응형

'Pillow 이미지 서치(Image search) 1' 은 target과 source의 모든 픽셀이 정확히 일치하는 경우만 True로 판단 하기 때문에 PNG나 BMP같은 무손실 압축 그래픽 파일에만 적용 가능하다. JPEG같은 손실 압축 그래픽 파일은 target과 source의 오차를 감안해야 한다.

 

2018/11/30 - [Software/Python] - Pillow 이미지 서치(Image Search) 1

2019/07/08 - [Software/OpenCV] - Template Matching(Image Searching) - 부분 이미지 검색

2019/07/10 - [Software/OpenCV] - Template Matching(Image Searching) for multiple objects - 반복되는 이미지 모두 찾기

2019/07/12 - [Software/OpenCV] - Template Matching(Image Searching) with a mask for multiple objects - 마스크를 이용해 (배경이 다른) 반복되는 이미지 모두 찾기

 

Target: 93 X 47

 

Source: 600 X 600

 

강아지의 앞발에 위치한 타겟 위치를 찾아 보자.

 

Tolerance: 30

Step: 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from PIL import Image
from PIL import ImageDraw
from PIL import ImageChops
from PIL import ImageStat
import sys
import time
 
source = Image.open("source.jpg")
sx, sy = source.size
target = Image.open("target.jpg")
tx, ty = target.size
tolerance = 30 # 오차 범위는 30 정도면 적당한거 같다.
step = 2 # 모든 픽셀을 검사하면 너무 오랜 시간이 걸린다. 한 개 건너 한 개 픽셀만 검사.
 
print("Source size: ", source.size)
print("Target size: ", target.size)
 
trial = 0 # Image search 시도 횟수.
 
def Search(cx, cy, tolerance):
    compare = source.crop((cx, cy, cx + tx, cy + ty)) # 소스에서 타겟으로 판단되는 위치의 이미지를 타겟 사이즈 만큼 잘라낸다.
    # Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
    print("Compare size: ", compare.size)
 
    diff = ImageChops.difference(compare, target) # 타겟과 타겟으로 판단되는 부분의 픽셀값 비교.
    stat = ImageStat.Stat(diff)
    global trial
    if max(max(stat.extrema[0]), max(stat.extrema[1]), max(stat.extrema[2])) <= tolerance:
        print("Target found(Min, max): ", stat.extrema)
        return True
    else:
        trial += 1
        return False
 
draw = ImageDraw.Draw(source)    # Creates an object that can be used to draw in the given image.
start = time.time()
 
for y in range(sy - ty):                # 소스의 처음부터 타겟 사이즈를 뺀 위치 까지 전체 검색을 시작 한다.
    for x in range(0, sx - tx, step):    # 처음 (10 X 10)개 픽셀의 값이 비슷 하다면 Search()로 타겟 사이즈 전체를 다시 확인한다.
        compare = source.crop((x, y, x + 10, y + 10))
        partial_target = target.crop((001010))
        diff = ImageChops.difference(compare, partial_target) # 각 픽셀값 차의 절대값이 반환 된다.
        # Returns the absolute value of the pixel-by-pixel difference between the two images.
        stat = ImageStat.Stat(diff)
 
        if max(max(stat.extrema[0]), max(stat.extrema[1]), max(stat.extrema[2])) < tolerance:
            if Search(x, y, tolerance) == True:
                print("Top left point: (%d, %d)" %(x, y))
                print("Center of targe point: (%d, %d)" %(x + target.width / 2, y + target.height / 2))
                print("Number of total wrong detection: ", trial)
                draw.rectangle((x, y, x + target.width, y + target.height), outline = (25500))
                # Draws a rectangle. 소스 이미지의 타겟 부분에 빨간 사각형을 그린다.
                end = time.time()
                print("Seraching time: ", end - start)
                source.show()
                sys.exit()
            else:
                print("At (%d, %d): Target not found" %(x, y))
                print("Wrong detection count: ", trial)
 
end = time.time()
print("Image search failed.")
print("Seraching time: ", end - start)
 
 

 

소스를 입력하고 빌드한다.

 

 

결과

 

123번 잘못된 지점을 검색했고 (232, 497)위치의 Target을 찾는데 총 15.66초가 걸렸다.

JPEG파일의 손실 압축 때문에 Target과 Source의 픽셀이 최대 RGB(16, 9, 15)만큼 차이가 발생 했다.

Target을 찾지 못한다면 Step과 Tolerance 값을 적당히 수정해야 한다.

 

반응형
Posted by J-sean
:
반응형

Pillow 모듈을 사용해 큰 이미지에서 작은 부분을 찾을 수 있다. 예를 들어 아래 Target과 같이 작은 부분을 큰 Source에서 찾아야 하는 경우이다.


2018/12/02 - [Software/Python] - Pillow 이미지 서치(Image Search) 2

2019/07/08 - [Software/OpenCV] - Template Matching(Image Searching) - 부분 이미지 검색

2019/07/10 - [Software/OpenCV] - Template Matching(Image Searching) for multiple objects - 반복되는 이미지 모두 찾기

2019/07/12 - [Software/OpenCV] - Template Matching(Image Searching) with a mask for multiple objects - 마스크를 이용해 (배경이 다른) 반복되는 이미지 모두 찾기


Target:


Source:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from PIL import Image
from PIL import ImageDraw
from PIL import ImageChops
from PIL import ImageStat
import sys
 
source = Image.open("source.bmp")
sx, sy = source.size
target = Image.open("target.bmp")
tx, ty = target.size
 
print("Source size: ", source.size)
print("Target size: ", target.size)
 
trial = 0 # Image search 시도 횟수.
 
def Search(cx, cy):
    #for y in range(ty):
    #    for x in range(tx):
    #        if target.getpixel((x, y)) == source.getpixel((cx + x, cy + y)):
    #            continue
    #        else:
    #            return False
    #return True
 
    compare = source.crop((cx, cy, cx + tx, cy + ty)) # 소스에서 타겟으로 판단되는 위치의 이미지를 타겟 사이즈 만큼 잘라낸다.
    # Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
    print("Compare size: ", compare.size)
 
    diff = ImageChops.difference(compare, target) # 타겟과 타겟으로 판단되는 부분의 픽셀값 비교.
    stat = ImageStat.Stat(diff)
    global trial
    if stat.sum == [000]:
        print("Target found(checksum): ", stat.sum)
        return True
    else:
        trial += 1
        return False
 
draw = ImageDraw.Draw(source)    # Creates an object that can be used to draw in the given image.
 
for y in range(sy - ty):        # 소스의 처음부터 타겟 사이즈를 뺀 위치 까지 검색을 시작 한다.
    for x in range(sx - tx):    # 처음 (2 X 2)개 픽셀의 값이 같다면 Search()로 타겟 사이즈 전체를 다시 확인한다.
        if source.getpixel((x, y)) == target.getpixel((00)) and source.getpixel((x + 1, y)) == target.getpixel((10)) \
            and source.getpixel((x, y + 1)) == target.getpixel((01)) and source.getpixel((x + 1, y + 1)) == target.getpixel((11)):
            if Search(x, y) == True:
                print("Top left point: (%d, %d)" %(x, y))
                print("Center of targe point: (%d, %d)" %(x + target.width / 2, y + target.height / 2))
                print("Number of total wrong detection: ", trial)
                draw.rectangle((x, y, x + target.width, y + target.height), outline = (25500))
                # Draws a rectangle. 소스 이미지의 타겟 부분에 빨간 사각형을 그린다.
                source.show()
                sys.exit()
            else:
                print("At (%d, %d): Target not found" %(x, y))
                print("Wrong detection count: ", trial)
 
print("Image search failed.")
cs




결과: 리트리버의 앞발 쪽에서 Target을 찾았다.

반응형
Posted by J-sean
: