前言
这部分是将heatmap里的图片crop成手骨的剪切图
这是几个函数的解释
cv2.findContours()
cv2.imread()
cv2.threshold
一、crop_patches.py
1.代码解释
import cv2
import numpy as np
import os
def crop(img, mask): # 定义剪裁的函数
index = np.where(mask > 0) # 输出满足条件 (即非0) 元素的坐标
top = np.min(index[0]) # 求index[0]中最小元素
bottom = np.max(index[0]) # ~求最大元素
left = np.min(index[1]) # 同理
right = np.max((index[1]))
# extract hand region
# if top > 200:
# top =top -200
# elif top > 100:
# top = top -100
# extract region1
# if left>100:
# left=left-70
croped_img = img[top:bottom, left:right]
return croped_img
def maskout(img, mask): #
index = np.where(mask > 0)
top = np.min(index[0])
bottom = np.max(index[0])
left = np.min(index[1])
right = np.max((index[1]))
img[top:bottom, left:right] = np.random.randint(255)
return img
def find_max_component(mask):#找到最大组成部分
#contours返回一个list,list中每个元素都是图像中的一个轮廓
#hierarchy返回可选的层级结果,这是一个ndarray,其中的元素个数和轮廓个数相同
contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # 查找检测物体的轮廓
area = []
for i in range(len(contours)):
area.append(cv2.contourArea(contours[i]))#返回值与轮廓contours[i]的真实面积
max_ind = np.argmax(area)
print(area)
for ind in range(len(contours)):
if ind != max_ind:
cv2.fillConvexPoly(mask, contours[ind], 0)#填充凸多边形
return mask
if __name__ == "__main__":
path_list = os.listdir('train/')
path_list.sort()
print(path_list)#由`xxx.png`组成的列表
kernel = np.ones((5, 5), np.uint8)
for path in path_list:
img = cv2.imread('train/' + path, 0)## 使用灰度图方式加载一张彩色照片
heatmap = cv2.imread('heatmap/' + path, 0)
#cv2.THRESH_BINARY 表示阈值的二值化操作,大于阈值40使用255表示,小于阈值40使用0表示
#返回的ret为阈值,第mask为结果图像
ret, mask = cv2.threshold(heatmap, 40, 255, cv2.THRESH_BINARY)
mask = find_max_component(mask)
# mask = cv2.dilate(mask,kernel,iterations=1)
# cv2.imwrite('patches/'+path,mask)
# img = img*mask
# cv2.imwrite('patches/'+path,img)
print(path)
croped_img = crop(img, mask)
cv2.imwrite('Hand/' + path, croped_img)
# MaskImg = maskout(img,mask)
# cv2.imwrite('Maskout/'+path,MaskImg)
总结
这段代码不难所以解释的很简单,后期如果有新的感悟,会继续补充!