代码:
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
from skimage import morphology
import copy
image_path = r"E:\n1\two"
save = r"E:\n1\save2"
path_list = os.listdir(image_path)
times = 1
def changezero2255(img,img1):
er = img.astype("int")
er[er == 1] = 255
er[er == 0] = 0
image = np.zeros_like(img1)
image[:, :, 0] = er
image[:, :, 1] = er
image[:, :, 2] = er
return image
for i in path_list:
print(i)
img1 = cv2.imread(image_path + "/"+i)
yuv1 = cv2.cvtColor(img1, cv2.COLOR_BGR2YUV)
v1 = yuv1[:, :, 2]
v1_binary = ~np.logical_not(v1 > 127)
yuv_img_one = morphology.remove_small_objects(v1_binary, min_size=500, connectivity=1)
one_img = yuv_img_one.astype('uint8')
contours, _ = cv2.findContours(one_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print(times, "个数:", len(contours))
for con in contours:
area = -cv2.contourArea(con, True)
if area < 2000:
x, y, w, h = cv2.boundingRect(con)
cv2.rectangle(one_img, (x, y), (x + w, y + h), (0, 0, 0), -1)
image1 = changezero2255(one_img,img1)
image2 = copy.deepcopy(image1)
contours_tubao, _ = cv2.findContours(one_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours_tubao:
tubao = cv2.convexHull(cnt)
cv2.polylines(image2, [tubao], True, (255, 0, 255), 10)
print("凸包:",tubao[0])
image3 = copy.deepcopy(image1)
contours_jinsi, _ = cv2.findContours(one_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours_jinsi:
jinsi = cv2.approxPolyDP(cnt, 3, True)
cv2.polylines(image3, [jinsi ], True, (255, 255, 0), 3)
print("近似:", jinsi[0])
gujiaimage = copy.deepcopy(one_img)
gujia = morphology.skeletonize(gujiaimage)
image4 = changezero2255(gujia,img1)
save_p1 = save + "\\" +"yuantu" + i
cv2.imwrite(save_p1, image1)
save_p2 = save + "\\" + "tubao" + i
cv2.imwrite(save_p2, image2)
save_p3 = save + "\\" + "jinsi" + i
cv2.imwrite(save_p3, image3)
save_p4 = save + "\\" + "gujia" + i
cv2.imwrite(save_p4, image4)
plt.imshow(image2)
plt.title(f"times: {times} tubao: {i}")
plt.show()
times += 1
原图:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bbcb1ea0dd31578c777761f2d99823f9.jpeg)
处理后:
骨架:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0be6633fef091eb5cb76d6b364efb622.jpeg)
近似:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ba7a77ae294aea51c4b59a872a3f415f.jpeg)
凸包:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a9959ebebb8565a5e0f567748d7ca7dd.jpeg)