骨龄预测系列(三)


前言

这部分是将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)




总结

这段代码不难所以解释的很简单,后期如果有新的感悟,会继续补充!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值