Пример #1
0
 def argsort(self, axis=1, desc=False):
     if axis == 0:
         sortFlags = cv.SORT_EVERY_COLUMN
     elif axis == 1:
         sortFlags = cv.SORT_EVERY_ROW
     if desc:
         sortFlags += cv.SORT_DESCENDING
     else:
         sortFlags += cv.SORT_ASCENDING
     out = Mat(self.shape, dtype=int32, UMat=self.UMat)
     cv.sortIdx(self._, sortFlags, out._)
     return out
Пример #2
0
    def img_process(self, img_path='', filename='default'):
        img = cv2.imread(img_path)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        #cv2.imshow('%s'%img_path, img)

        #blur = cv2.GaussianBlur(gray, (5, 5), 0)
        ret, bin_img = cv2.threshold(gray, 125, 255, cv2.THRESH_BINARY)
        #cv2.imshow('%s bin_img'%img_path, bin_img)
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
        bin_img = cv2.morphologyEx(bin_img, cv2.MORPH_CLOSE, kernel)
        #cv2.imshow("%s close"%img_path, bin_img)
        bin_img, contours, hierarchy = cv2.findContours(
            bin_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
        print len(contours)

        idx = 0
        areas = np.zeros(len(contours))
        for con in contours:
            areas[idx] = cv2.contourArea(con)
            idx += 1
        areas_s = cv2.sortIdx(areas,
                              cv2.SORT_DESCENDING | cv2.SORT_EVERY_COLUMN)
        for idx in areas_s:
            if areas[idx] < 200:
                break
            poly_img = np.zeros(bin_img.shape, dtype=np.uint8)
            cv2.drawContours(poly_img, contours, idx, [255, 255, 255], -1)
            poly_img = poly_img & bin_img
            #cv2.imshow('%scontour %d' % (img_path, idx), poly_img)
            cv2.imwrite('%s_%d.jpg' % (img_path.split('.')[0], idx), poly_img)
Пример #3
0
def contours_sort_idx(contours):
    """轮廓排序
    """
    # 按面积排序
    areas = numpy.zeros(len(contours))
    for idx,cont in enumerate(contours): 
        areas[idx] = cv2.contourArea(cont)

    return cv2.sortIdx(areas, cv2.SORT_DESCENDING | cv2.SORT_EVERY_COLUMN)
Пример #4
0
    def nms(self, boxes, iou_thresh):
        """ This Function takes the output of yolov3 and loops though all
            to know which ones are similar, This function keeps the best 
            prediction for an object
        """
        # If there are no bounding boxes do nothing
        if len(boxes) == 0:
            return boxes

        # Create a PyTorch Tensor to keep track of the detection confidence
        # of each predicted bounding box
        det_confs = np.zeros(len(boxes))

        # Get the detection confidence of each predicted bounding box
        for i in range(len(boxes)):
            det_confs[i] = boxes[i][4]

        # Sort the indices of the bounding boxes by detection confidence value in descending order.
        # We ignore the first returned element since we are only interested in the sorted indices
        # print(f'det_confs --> {det_confs}')
        # _,sortIds = torch.sort(det_confs, descending = True)
        sortIds = cv2.sortIdx(det_confs, -1).reshape(-1)
        # print(f'sort --> {sortIds}')
        # print(f'_ and sortid {_} and {sortIds}')
        # Create an empty list to hold the best bounding boxes after
        # Non-Maximal Suppression (NMS) is performed
        best_boxes = []

        # Perform Non-Maximal Suppression
        for i in range(len(boxes)):

            # Get the bounding box with the highest detection confidence first
            box_i = boxes[sortIds[i]]

            # Check that the detection confidence is not zero
            if box_i[4] > 0:

                # Save the bounding box
                best_boxes.append(box_i)

                # Go through the rest of the bounding boxes in the list and calculate their IOU with
                # respect to the previous selected box_i.
                for j in range(i + 1, len(boxes)):
                    box_j = boxes[sortIds[j]]

                    # If the IOU of box_i and box_j is higher than the given IOU threshold set
                    # box_j's detection confidence to zero.
                    if self.boxes_iou(box_i, box_j) > iou_thresh:
                        box_j[4] = 0

        return best_boxes
Пример #5
0
def pixelOfDarkChannelImage(img, ratio):
	h, w = img.shape[: 2]
	numPixels = h * w 
	numSelectPixels = int(numPixels * ratio)
	newImg = np.zeros(h*w)
	pixels = []
	k = 0
	newImg = img.reshape(1, h*w)[0]
	pixelIndexs = cv2.sortIdx(newImg, cv2.SORT_EVERY_COLUMN + cv2.SORT_DESCENDING)
	for i in range(numSelectPixels):
		rowOfPixel = pixelIndexs[i] / w
		colOfPixel = pixelIndexs[i] % w
		pixels.append([rowOfPixel, colOfPixel])
	return pixels, numSelectPixels
Пример #6
0
 def saltErase(img, contours):
     # 按面积排序
     areas = np.zeros(len(contours))
     idx = 0
     for contour in contours:
         areas[idx] = cv2.contourArea(contour)
         idx = idx + 1
     areas_s = cv2.sortIdx(
         areas, cv2.SORT_DESCENDING | cv2.SORT_EVERY_COLUMN)
     imgClear = np.zeros(img.shape, dtype=np.uint8)
     #                for idx in areas_s:
     #                    if areas[idx] < 800:
     #                        break
     #                     # 绘制轮廓图像,通过将thickness设置为-1可以填充整个区域,否则只绘制边缘
     #                    cv2.drawContours(imgClear, contours, idx, [255, 255, 255], -1)
     cv2.drawContours(imgClear, contours, areas_s[0],
                      [255, 255, 255], -1)
     imgClear = imgClear & img
     return imgClear
Пример #7
0
        print("rects[%i] = [(%3d,%3d) from (%3d,%3d)] %5d" %
              (i, x, y, w, h, a))
    print()


rands = np.zeros((5, 5), np.uint16)  # 5행 4열 행렬 생성
starts = cv2.randn(rands[:, :2], 100, 50)  # 0~4행까지 시작좌표 랜덤 생성
ends = cv2.randn(rands[:, 2:-1], 300, 50)  # 5~9행까지 종료좌표 랜덤 생성

sizes = cv2.absdiff(starts, ends)  # 시작좌표와 종료좌표간 차분 절대값
areas = sizes[:, 0] * sizes[:, 1]
rects = rands.copy()
rects[:, 2:-1] = sizes
rects[:, -1] = areas

idx = cv2.sortIdx(areas, cv2.SORT_EVERY_COLUMN).flatten()
# idx = np.argsort(areas, axis=0)

print_rects(rects)
print_rects(rects[idx.astype('int')])

## 리스트 생성 방식
# rects = ["[(%3d,%3d) from (%3d,%3d)]" %(p[0], p[1], s[0], s[1])
#          for p, s in zip(starts, sizes)]				# 시작좌표와 크기로 리스트 생성
# areas = [s[0]*s[1] for s in sizes]					# 넓이 계산 및 리스트에 저장
#
# # 정렬 후, 정렬 원소의 원본 좌표 반환
# sort_idx = cv2.sortIdx(np.array(areas), cv2.SORT_EVERY_COLUMN)
# sort_idx = map(int , sort_idx)
#
# print("-" * 46)                             	# 라인 출력
Пример #8
0
from PIL import Image
from pylab import *
import cv2

img = cv2.imread('018.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

contoures, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                                        cv2.CHAIN_APPROX_NONE)
areas = np.zeros(len(contoures))
idx = 0
for cont in contoures:
    areas[idx] = cv2.contourArea(cont)
    idx = idx + 1
areas_s = cv2.sortIdx(areas, cv2.SORT_DESCENDING | cv2.SORT_EVERY_COLUMN)
print areas_s

# (b8, g8, r8) = cv2.split(img)
#
# # 对每个区域进行处理
# for idx in areas_s :
#     if areas[idx] < 100 :
#         break
#
#     # 绘制区域图像,通过将thickness设置为-1可以填充整个区域,否则只绘制边缘
#     poly_img = np.zeros(img.shape, dtype = np.uint8 )
#     cv2.drawContours(poly_img, contoures, idx, [255,255,255], -1)
#     poly_img = poly_img & img
#
#     # 得到彩色的图像
Пример #9
0
    def save_png(self, src, imgray, contours, home_path):
        width = src.shape[1]
        height = src.shape[0]

        # 创建存储轮廓点的文件夹
        if not os.path.exists(home_path + "\\contours"):
            os.mkdir(home_path + "\\contours")
        # 创建存储图片的文件夹
        if not os.path.exists(home_path + "\\img"):
            os.mkdir(home_path + "\\img")
        # 创建存储相对坐标的文件夹
        if not os.path.exists(home_path + "\\offset"):
            os.mkdir(home_path + "\\offset")

        # 按面积排序
        areas = np.zeros([len(contours)])
        index = 0  # 面积的下标指针

        # 遍历轮廓,计算每个轮廓的面积
        for contour in contours:
            areas[index] = cv2.contourArea(contour)
            index = index + 1
        # 对轮廓按面积排序,sortIdx能够得到这些值在原数组中的序号
        areas_s = cv2.sortIdx(areas,
                              cv2.SORT_DESCENDING + cv2.SORT_EVERY_COLUMN)
        (b8, g8, r8, a8) = cv2.split(src)

        # 对每个区域进行处理
        for index in areas_s:
            if areas[index] < width * height * 0.001 or areas[
                    index] > width * height * 0.1:
                continue
            m = cv2.moments(contours[index.tolist()[0]])

            # 计算中心矩
            cx = int(m['m10'] / m['m00'])
            cy = int(m['m01'] / m['m00'])

            offset_x = (m['m10'] / m['m00']) / height
            offset_y = (m['m01'] / m['m00']) / width

            # 获得轮廓的边缘点
            np.savetxt('{0}\\contours\\{1},{2}'.format(home_path, str(cx),
                                                       str(cy)),
                       (contours[index.tolist()[0]]).reshape((-1, 2)),
                       fmt='%d',
                       delimiter=',')
            # 获得相对坐标
            contours_points = (contours[index.tolist()[0]]).reshape((-1, 2))
            x_ = contours_points[:, 0]
            y_ = contours_points[:, 1]
            x_ = x_ / height
            y_ = y_ / width
            x_ = x_[:, np.newaxis]
            y_ = y_[:, np.newaxis]
            contours_points = np.concatenate((x_, y_), axis=1)
            np.savetxt(home_path + '\\offset\\' + str(cx) + ',' + str(cy),
                       contours_points,
                       fmt='%f',
                       delimiter=',')

            # 绘制区域图像,通过将thickness设置为-1可以填充整个区域,否则只绘制边缘
            temp_img = np.zeros(imgray.shape, dtype=np.uint8)
            cv2.drawContours(temp_img, contours, index, [255, 255, 255], -1)
            # 结合灰度图掩膜
            # temp_img = temp_img & imgray

            # 得到彩色的图像
            color_img = cv2.merge(
                [b8 & temp_img, g8 & temp_img, r8 & temp_img, a8 & temp_img])

            # cv2.imshow("img",color_img) 为什么会闪退?
            cv2.imwrite(
                home_path + '\\img\\' + str(cx) + ',' + str(cy) + '.png',
                color_img)
Пример #10
0
# with cv2
# sort : row , ascending
sort1 = cv2.sort(matrix, cv2.SORT_EVERY_ROW)
# sort : row , descending
sort2 = cv2.sort(matrix, cv2.SORT_EVERY_ROW + cv2.SORT_DESCENDING)
# sort : col , ascending
sort3 = cv2.sort(matrix, cv2.SORT_EVERY_COLUMN)
# sort : col , descending
sort4 = cv2.sort(matrix, cv2.SORT_EVERY_COLUMN + cv2.SORT_DESCENDING)

# with Numpy
# sort : x axis
sort5 = np.sort(matrix, axis=1)
# sort : y axis
sort6 = np.sort(matrix, axis=0)

# return sort Index - 행렬의 원소를 직접 정렬하지 않고, 정렬된 원소의 원 Index를 반환한다.

# cv2
Idx_sort1 = cv2.sortIdx(matrix, cv2.SORT_EVERY_ROW)
'''
[[2 0 1 4 3]
 [4 1 2 3 0]
 [1 0 3 4 2]]
'''
Idx_sort2 = cv2.sortIdx(matrix, cv2.SORT_EVERY_COLUMN)

# numpy
Idx_sort3 = np.argsort(matrix, axis=0)  # y axis
Пример #11
0
import numpy as np, cv2

m = np.random.randint(0, 100, 15).reshape(3, 5)  # 임의 난수 생성

m_sort1 = cv2.sortIdx(m, cv2.SORT_EVERY_ROW)  # 행렬 원소의 원본 좌표
m_sort2 = cv2.sortIdx(m, cv2.SORT_EVERY_COLUMN)
m_sort3 = np.argsort(m, axis=0)  # 세로축 정렬

print("[m1] = \n%s\n" % m)
print("[m_sort1] = \n%s\n" % m_sort1)
print("[m_sort2] = \n%s\n" % m_sort2)
print("[m_sort3] = \n%s\n" % m_sort3)