gpt4 book ai didi

python - 在 opencv python 中将边界应用于我的图像

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:56 26 4
gpt4 key购买 nike

This is the image我试图为文件夹中的图像赋予适当的形状,但无法获得完美的结果。以下是一种类型的示例:

以下是我为包含此类图像的文件夹所做的编码:

''''代码''''

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)

最佳答案

尝试使用 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)

弯头.png:

enter image description here

elbow_border.png:

enter image description here

关于python - 在 opencv python 中将边界应用于我的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com