Применить границы к моему изображению в OpenCV Python - PullRequest
1 голос
/ 25 октября 2019

Это изображение Я пытаюсь придать правильную форму изображениям в своей папке, но не могу добиться такого идеального результата. Ниже приведен пример одного типа:

Ниже приведена кодировка, которую я сделал для своей папки, содержащей изображения этого типа:

'' '' code '' ''

import cv2
import numpy as np
import glob

path = r'C:\Users\User\Desktop\A\*.jpg'

def k_function(image,k):
    z= image.reshape((-1,4))
    z=np.float32(z)
    criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    ret,label,center=cv2.kmeans(z,k,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
    center = np.uint8(center)
    res = center[label.flatten()]
    res2 = res.reshape((image.shape))
    return res2

def noise_function(image):
    kernel = np.ones((2, 2), np.uint8)
    closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, 
                            kernel, iterations = 2)
    bg = cv2.dilate(closing, kernel, iterations = 1)
    dist_transform = cv2.distanceTransform(closing, cv2.DIST_L2, 0)
    ret, fg = cv2.threshold(dist_transform, 0.02
                        * dist_transform.max(), 255, 0)
    return fg

def filling(thresh):
    im_floodfill = thresh.copy()
    h, w = thresh.shape[:2]
    mask = np.zeros((h+2, w+2), np.uint8)
    cv2.floodFill(im_floodfill, mask,(60,60),255);
    im_floodfill_inv = cv2.bitwise_not(im_floodfill)
    n = thresh | im_floodfill_inv
    return n


for i, img in enumerate(glob.glob(path)):
    img1 = cv2.imread(img)
    n = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) 
    b= k_function(n,2)
    nm, thresh1 = cv2.threshold(b, 127, 255, cv2.THRESH_BINARY_INV);
    fill = filling(thresh1)
    noise = noise_function(fill)
    cv2.imwrite(r'C:\Users\User\Desktop\New folder\image{}.jpg'.format(i),noise)

Ответы [ 2 ]

0 голосов
/ 26 октября 2019

Я бы подошел к этому немного по-другому в Python / OpenCV. Я бы преобразовал в HSV и порог насыщения канала. Затем используйте морфологию open для сглаживания контура.

Ввод (обрезка из вашего сообщения):

enter image description here

import cv2

# load image as HSV and select saturation
img = cv2.imread("finger.png")
sat = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[:,:,1]

# threshold the saturation channel
ret, thresh = cv2.threshold(sat,25,255,0)

# apply morphology open to smooth the outline
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (19,19))
smoothed = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

# write result to disk
cv2.imwrite("finger_smoothed.png", smoothed)

cv2.imshow("SAT", sat)
cv2.imshow("THRESH", thresh)
cv2.imshow("SMOOTHED", smoothed)
cv2.waitKey(0)
cv2.destroyAllWindows()


Результат:

enter image description here

0 голосов
/ 26 октября 2019

Попробуйте использовать copyMakeBorder для создания границы. Похоже, вы пытаетесь использовать floodFill, и я так и не понял, как это должно работать.

import cv2

image = cv2.imread('elbow.png')

image = cv2.copyMakeBorder(image, 10, 0, 0, 10, cv2.BORDER_CONSTANT)

cv2.imwrite('elbow_border.png', image)

elbow.png:

enter image description here

elbow_border.png:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...