不多说辽,最近太忙了代码备注应该够清晰。。。
代码如下
import json
from typing import Tuple
import cv2
# from utils import get_mask_bounding, json_to_dict
import numpy as np
from os.path import join, basename
from os import listdir, makedirs
ori_dir = 'C://Users/27651\Desktop\crops_canopy\FirstStage\data\TIF'
tgt_dir = 'C://Users/27651\Desktop\crops_canopy\FirstStage\data\canopy_result_no_mask'
mask_flag = True
def get_mask_bounding(mask: np.ndarray):
x_min = np.min(mask[:, 0])
x_max = np.max(mask[:, 0])
y_min = np.min(mask[:, 1])
y_max = np.max(mask[:, 1])
return np.array([[x_min, y_min, x_max, y_max]])
def json_to_dict(json_path):
with open(json_path) as o:
content = o.read()
d = json.loads(content)
return d
##通道分离融合函数,输入的路径为data\canopy_result_no_mask\0_20210326,即去掉图片的后缀
def afterCrop(crop_img_path):
img = cv2.imread(crop_img_path+'.tif', -1)
b = np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
g = np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
r = np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
nr = np.zeros((img.shape[0],img.shape[1]),dtype=img.dtype)
b[:,:] = img[:,:,0] # 复制 b 通道的数据
g[:,:] = img[:,:,1] # 复制 g 通道的数据
r[:,:] = img[:,:,2] # 复制 r 通道的数据
nr[:,:] = img[:,:,3] # 复制 nr 通道的数据
merged_b_g_nr = np.dstack([b,g,nr])
merged_b_nr_r = np.dstack([b,nr,r])
merged_nr_g_r = np.dstack([nr,g,r])
cv2.imwrite(crop_img_path+"merged_b_g_nr.tif" , merged_b_g_nr)
cv2.imwrite(crop_img_path+"merged_b_nr_r.tif", merged_b_nr_r)
cv2.imwrite(crop_img_path+"merged_nr_g_r.tif", merged_nr_g_r)
##剪切函数
def crop_img(img_path: str):
date = img_path.split('_')[0]
ano_path = img_path.split('.')[0] + '.json'
img = cv2.imread(join(ori_dir, img_path),-1)
h, w = img.shape[:2]
ano = json_to_dict(join(ori_dir, ano_path))
shapes = ano['shapes']
for i in range(len(shapes)):
output_path = '{}_{}.tif'.format(i, date)
points = np.array(shapes[i]['points'], dtype=int)
x_min, y_min, x_max, y_max = get_mask_bounding(points)[0]
if x_min < 0 or y_min < 0 or x_max >= w or y_max >= h:
ins_img = np.zeros(shape=[1, 1, 4], dtype=np.uint8)
cv2.imwrite(join(tgt_dir, output_path), ins_img)
continue
ins_img = img[y_min:y_max, x_min:x_max]
if not mask_flag:
cv2.imwrite(join(tgt_dir, output_path), ins_img)
continue
points[:, 0] -= x_min
points[:, 1] -= y_min
mask = np.zeros(ins_img.shape[:2], np.uint8)
points = np.array([points], dtype=int)
cv2.polylines(mask, points, 1, 255)
cv2.fillPoly(mask, points, 255)
dst = cv2.bitwise_and(ins_img, ins_img, mask=mask)
cv2.imwrite(join(tgt_dir, output_path), dst)
after_output_path = '{}_{}'.format(i, date)
crop_img = join(tgt_dir, after_output_path)
afterCrop(crop_img)
if __name__ == '__main__':
file_ls = [f for f in listdir(ori_dir) if 'tif' in f]
for f in file_ls:
print(f)
crop_img(f)
效果
?tips:图像和Json文件放在同一个文件夹
|