コード例 #1
0
def PPT(ImgNo, defThr=127):
    img = cv2.imread(impDef.select_img(ImgNo))
    img2 = img.copy()
    imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    ret, thr = cv2.threshold(imgray, defThr, 255, 0)
    contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    cnt = contours[0]
    cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)  # contour를 녹색으로 그림

    outside = (55, 70)
    inside = (140, 150)

    # (55, 70)으로 설정된 outside와 (140, 150)으로 설정된 inside에 대해 별보양의 Contour까지 최단거리를 구함
    # cv2.pointPolygonTest()함수의 3번째 인자가 True로 설정되면 Contour와 점 사이의 최단거리를 리턴
    # cv2.pointPolygonTest()함수의 3번째 인자가 False로 설정되면 주어진 점이 Contour의 외부에 있으면 -1, Contour위에 있으면 0,
    # Contour내부에 있으면 1을 리턴
    dist1 = cv2.pointPolygonTest(cnt, outside, True)
    dist2 = cv2.pointPolygonTest(cnt, inside, True)

    print('Contour에서 (%d, %d)까지의 거리 : %.3f' % (outside[0], outside[1], dist1))
    print('Contour에서 (%d, %d)까지의 거리 : %.3f' % (inside[0], inside[1], dist2))

    cv2.circle(img, outside, 3, (0, 255, 255), -1)  # 노란색 점
    cv2.circle(img, inside, 3, (255, 0, 255), -1)  # 분홍색 점

    cv2.imshow('defects', img)
    impDef.close_window()
コード例 #2
0
    def contour_containing_point(self, x, y, boolDebug=True):
        "Returns the contour under which the co-ordinate falls"

        for Class in range(
                self.num_classes):  # for contours in self.contours_list:
            contours = self.contours_list[Class]
            for contour in contours:
                if (cv2.pointPolygonTest(
                        contour=contour, pt=(x, y), measureDist=False) >= 0
                        and contour is not self.obj_selected):
                    if boolDebug:
                        print(f"{self.classes[Class]}")
                    return contour
                else:
                    pass
        return []
def FilterOutOverlapPoint(Input_contours, Center_positions):
    inside_contour_count = 0
    ret = 0
    output_centroid = []
    i=0
    for contour in Input_contours:
        inside_contour_count = 0
        i=0
        # for center_position in Center_positions:
        while i < len(Center_positions):
            ret = cv.pointPolygonTest(contour,(Center_positions[i][0],Center_positions[i][1]),False)
            if ret == 0 or ret == 1:
                if inside_contour_count >= 1:
                    None
                else:
                    output_centroid.append(Center_positions[i])
                inside_contour_count+=1
            i+=1
    return output_centroid
コード例 #4
0
ファイル: hand_fD.py プロジェクト: watson1101/AI-project
    def reconstruct(self, img, descirptor_in_use):
        """由傅里叶描述子重建轮廓图

        :param res: 输入图像,傅里叶描述子
        :return: 重绘图像
        """
        contour_reconstruct = np.fft.ifft(descirptor_in_use)  # 傅里叶反变换
        contour_reconstruct = np.array(
            [contour_reconstruct.real, contour_reconstruct.imag])
        contour_reconstruct = np.transpose(contour_reconstruct)  # 转换矩阵
        contour_reconstruct = np.expand_dims(contour_reconstruct,
                                             axis=1)  # 改变数组维度在axis=1轴上加1
        if contour_reconstruct.min() < 0:
            contour_reconstruct -= contour_reconstruct.min()
        contour_reconstruct *= img.shape[0] / contour_reconstruct.max()
        contour_reconstruct = contour_reconstruct.astype(np.int32, copy=False)
        # 中心点
        M = cv2.moments(contour_reconstruct)  # 计算第一条轮廓的各阶矩,字典形式
        center_x = int(M["m10"] / M["m00"])
        center_y = int(M["m01"] / M["m00"])

        black_np = np.ones(img.shape, np.uint8)  # 创建黑色幕布
        black = cv2.drawContours(black_np, contour_reconstruct, -1,
                                 (255, 255, 255), 3)  # 绘制白色轮廓
        black = cv2.circle(black, (center_x, center_y), 4, 255, -1)  # 绘制中心点
        cv2.circle(img, (center_x, center_y), 5, 255, -1)  # 绘制中心点

        point = []  # 二维数组转坐标形式
        for idx in range(len(contour_reconstruct)):
            str1 = str(
                contour_reconstruct[idx]).lstrip('[[').rstrip(']]').split(
                    " ")  # [[010 200]]去头尾,按空格分割['','10','200']
            while '' in str1:
                str1.remove('')  # 去空格
            point.append((int(str1[0]), int(str1[1])))
            if point[idx]:
                cv2.circle(black,
                           point[idx],
                           3, (0, 255, 255),
                           thickness=-1,
                           lineType=cv2.FILLED)
                cv2.putText(black,
                            "{}".format(idx),
                            point[idx],
                            cv2.FONT_HERSHEY_SIMPLEX,
                            0.6, (0, 0, 255),
                            2,
                            lineType=cv2.LINE_AA)
        # print(contour_reconstruct)
        print(point)
        # 凸包
        hull = cv2.convexHull(contour_reconstruct)  # 寻找凸包,得到凸包的角点
        print("部分凸包信息:")
        print(hull[0])  # [[194 299]](坐标)
        hull2 = cv2.convexHull(contour_reconstruct, returnPoints=False)
        print(hull2[0])  # [20](cnt中的索引)
        print(contour_reconstruct[31])  # [[146  33]]
        print(cv2.isContourConvex(hull))  # True是否为凸型
        dist = cv2.pointPolygonTest(contour_reconstruct, (center_x, center_y),
                                    True)  # 中心点的最小距离
        print(dist)
        cv2.polylines(img, [hull], True, (255, 255, 255), 3)  # 绘制凸包

        plt.figure(figsize=(10, 10))
        plt.subplot(1, 2, 1)
        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        plt.xlabel(u'凸包轮廓图', fontsize=20)
        plt.subplot(1, 2, 2)
        plt.imshow(cv2.cvtColor(black, cv2.COLOR_BGR2RGB))
        plt.xlabel(u'傅里叶描述子和重心', fontsize=20)
        plt.show()

        #cv2.imshow("contour_reconstruct", img)
        # cv2.imwrite('recover.png',img)
        return img
コード例 #5
0
import numpy as np
from cv2 import cv2
import matplotlib.pyplot as plt

img = cv2.imread(r'pictures\star.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 2, 1)
cnt = contours[0]

hull = cv2.convexHull(cnt, returnPoints=False)
# Remember we have to pass returnPoints = False while finding convex hull, in order to find convexity defects.
defects = cv2.convexityDefects(cnt, hull)
# It returns an array where each row contains these values - [ start point, end point, farthest point, approximate distance to farthest point ].

dist = cv2.pointPolygonTest(cnt, (50, 50), True)
# This function finds the shortest distance between a point (50, 50) in the image and a contour. It returns the distance which is negative when point is outside the contour, positive when point is inside and zero if point is on the contour.
# In the function, third argument is measureDist. If it is True, it finds the signed distance. If False, it finds whether the point is inside or outside or on the contour (it returns +1, -1, 0 respectively). Making it False gives about 2-3X speedup.

for i in range(defects.shape[0]):
    s, e, f, d = defects[i, 0]
    start = tuple(cnt[s][0])
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv2.line(img, start, end, [0, 255, 0], 2)
    cv2.circle(img, far, 5, [0, 0, 255], -1)

cv2.namedWindow("img", 0)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
コード例 #6
0
    (cv2.contourArea(cnt), cv2.boundingRect(cnt)[0], cv2.boundingRect(cnt)[1]),
    contours)
sizes.sort(key=getFirst)
biggest_letter_size = sizes[len(sizes) - 1][0]

flag_small_contours = mapFunc(
    lambda cnt: cv2.contourArea(cnt) / biggest_letter_size < cnt_area_thresh,
    contours)

for cnt_i in range(0, len(contours)):
    if (flag_small_contours[cnt_i]):
        curr_cnt = contours[cnt_i]
        x, y, w, h = cv2.boundingRect(curr_cnt)
        for i in range(0, w):
            for j in range(0, h):
                if (cv2.pointPolygonTest(curr_cnt,
                                         (x + i, y + j), False) >= 0):
                    edited_img[y + j, x + i] = 255
        continue

#print("boxes sizes")
#print(boxes_sizes)
#print("\nbounding boxes")
#print(bounding_boxes)
print("\nsizes")
print(list(sizes))
#print(cnt_area_thresh)
#bb=dict(zip(list(boxes_sizes),[list(boxes_sizes).count(i) for i in list(boxes_sizes)]))
#print(sorted(list(bb)))

cv2.imwrite("out.jpg", edited_img)
コード例 #7
0
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv2.line(img, start, end, [0, 255, 0], 2)
    cv2.circle(img, far, 5, [0, 0, 255], -1)

cv2.imshow('img', img)

# Point Polygon Test

# This function finds the shortest distance between a point in the image and a contour. It returns the distance which is negative when point is outside the contour, positive when point is inside and zero if point is on the contour.

# In the function, third argument is measureDist. If it is True, it finds the signed distance. If False, it finds whether the point is inside or outside or on the contour (it returns +1, -1, 0 respectively).

# If you don’t want to find the distance, make sure third argument is False, because, it is a time consuming process. So, making it False gives about 2-3X speedup.

dist = cv2.pointPolygonTest(cnt, (50, 50), True)
inside = cv2.pointPolygonTest(cnt, (50, 50), False)
print 'dist = ' + str(dist)
print 'inside = ' + str(inside)

# Match Shapes

# OpenCV comes with a function cv2.matchShapes() which enables us to compare two shapes, or two contours and returns a metric showing the similarity. The lower the result, the better match it is. It is calculated based on the hu-moment values. Different measurement methods are explained in the docs.

img1 = cv2.imread('resource/a_font.png', 0)
img2 = cv2.imread('resource/a_font.png', 0)

ret, thresh = cv2.threshold(img1, 127, 255, 0)
ret, thresh2 = cv2.threshold(img2, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 2, 1)
cnt1 = contours[0]