预处理
import argparse
import os
import json
from glob import glob
from PIL import Image
import numpy as np
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='/Users/yi/Desktop/vehicle_train_mask/')
parser.add_argument('--out_dir', default='/Users/yi/Desktop/annotations_vehicle_train_mask/')
return parser.parse_args()
def imgs(jpg_files):
if not os.path.isdir(get_args().out_dir):
os.makedirs(get_args().out_dir)
for jpg_name in jpg_files:
imagePath = get_args().input + jpg_name + ".png"
outPath = get_args().out_dir + jpg_name + ".png"
img = Image.open(imagePath)
img_array = np.array(img) # 把图像转成数组格式img = np.asarray(image)
shape = img_array.shape
print(img_array)
print(img_array.shape)
height = shape[0]
width = shape[1]
dst = np.zeros((height, width, 3))
for h in range(0, height):
for w in range(0, width):
r = img_array[h, w]
# print(r)
if r == 0:
dst[h, w] = (0, 0, 0)
else:
dst[h, w] = (1, 1, 1) # 替换为label
# (r, g, b) = img_array[h, w]
# if (r, g, b) == (255, 0, 0):
# img_array[h, w] = (1, 1, 1) # 替换为label
# dst[h, w] = img_array[h, w]
img2 = Image.fromarray(np.uint8(dst))
img2.save(outPath)
def main(args):
files = glob(args.input+ "*.png")
print(files)
files = [i.split("/")[-1].split(".png")[0] for i in files]
test_files = files
imgs(test_files)
if __name__ == '__main__':
main(get_args())
最大连通区域
import cv2
import os
import numpy as np
imaPath = '/Users/yi/Desktop/test_20210903_out/'
output = '/Users/yi/Desktop/test_20210903_out1/'
#
# import cv2
imaList = os.listdir(imaPath)
for files in imaList:
img = os.path.join(imaPath, files)
path_processed = os.path.join(output, files)
img = cv2.imread(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# cv2.imshow("img", gray)
# cv2.waitKey(1000)
ret, binary = cv2.threshold(gray, 156, 255, cv2.THRESH_BINARY)
# cv2.imshow("img", binary)
# cv2.waitKey(1000)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# 找到最大区域并填充
area = []
for j in range(len(contours)):
area.append(cv2.contourArea(contours[j]))
max_idx = np.argmax(area)
max_area = cv2.contourArea(contours[max_idx])
# print(max_area)
for k in range(len(contours)):
if k != max_idx:
print(k, 1)
cv2.fillPoly(img, [contours[k]], (198,215,20))
cv2.drawContours(img, contours[max_idx], -1, (0, 0, 255), 3)
cv2.imwrite(path_processed, img)
删除边界小凸起
import argparse
from glob import glob
import cv2
import os
import numpy as np
from PIL import Image
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='/Users/yi/Desktop/tu/')
parser.add_argument('--mask_dir', default='/Users/yi/Desktop/tu_out/')
parser.add_argument('--out_dir', default='/Users/yi/Desktop/tu_out_wx_result/')
return parser.parse_args()
def imgs(jpg_files):
print(jpg_files)
if not os.path.isdir(get_args().mask_dir)