Exemplo n.º 1
0
    def get_total_data_path(self, data_dir):
        total_paths, defect_lbs, lacuna_lbs, spoke_lbs, spot_lbs = [], [], [], [], []  # 이미지 path와 정답(label) 세트를 저장할 list

        image_paths = sorted(list(paths.list_images(data_dir)))
        for image_path in image_paths:
            # a. 이미지 전체 파일 path 저장
            total_paths.append(image_path)
            # b. 이미지 파일 path에서  이미지의 정답(label) 세트 추출
            (defect, lacuna, spoke,
             spot) = image_path.split(os.path.sep)[-2].split("_")
            defect_lbs.append(defect)
            lacuna_lbs.append(lacuna)
            spoke_lbs.append(spoke)
            spot_lbs.append(spot)

        defect_lbs = np.array(defect_lbs)
        lacuna_lbs = np.array(lacuna_lbs)
        spoke_lbs = np.array(spoke_lbs)
        spot_lbs = np.array(spot_lbs)

        defect_lbs = LabelBinarizer().fit_transform(defect_lbs)
        lacuna_lbs = LabelBinarizer().fit_transform(lacuna_lbs)
        spoke_lbs = LabelBinarizer().fit_transform(spoke_lbs)
        spot_lbs = LabelBinarizer().fit_transform(spot_lbs)

        return total_paths, defect_lbs, lacuna_lbs, spoke_lbs, spot_lbs
Exemplo n.º 2
0
    def test_load_data(dir=dir):
        print("[INFO] 학습할 이미지 로드 (로드시 경로들 무작위로 섞음)")
        imagePaths = sorted(list(paths.list_images(dir)))
        random.seed(42)
        random.shuffle(imagePaths)

        # data()와 labels 초기화
        datas = []  # 이미지 파일을 array 형태로 변환해서 저장할 list
        labels = []  # 해당 이미지의 정답(label) 세트를 저장할 list

        print("[INFO] 모든 이미지에 대하여 이미지 데이터와 라벨을 추출 ..")
        for imagePath in imagePaths:
            # a. 이미지를 로드하고, 전처리를 한 후 데이터 목록에 저장
            image = cv2.imread(imagePath)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = cv2.resize(image, (FLG.HEIGHT, FLG.WIDTH))
            image = img_to_array(image)
            datas.append(image)
            # b. 이미지 파일명에서  이미지의 정답(label) 세트 추출
            label = imagePath.split(os.path.sep)[-2]
            labels.append(label)

        print("[INFO] scale the raw pixel 의 밝기값을 [0, 1]으로 조정하고 np.array로 변경")
        x_val = np.array(datas, dtype="float") / 255.0
        y_val = np.array(labels)
        y_val = ImageGenerator.encode_one_hot(1, y_val)

        return x_val, y_val
    def get_total_data_path(self, data_dir):
        total_paths, total_labels = [], []  # 이미지 path와 정답(label) 세트를 저장할 list

        image_paths = sorted(list(paths.list_images(data_dir)))
        for image_path in image_paths:
            total_paths.append(image_path)
            label = image_path.split(os.path.sep)[-2]
            total_labels.append(label)

        return total_paths, total_labels
Exemplo n.º 4
0
    def get_total_data_path(self, data_dir):
        total_paths, total_labels = [], []  # 이미지 path와 정답(label) 세트를 저장할 list

        image_paths = sorted(list(paths.list_images(data_dir)))
        for image_path in image_paths:
            # a. 이미지 전체 파일 path 저장
            total_paths.append(image_path)
            # b. 이미지 파일 path에서  이미지의 정답(label) 세트 추출
            label = image_path.split(os.path.sep)[-2]
            total_labels.append(label)

        print('total_paths : ' + str(len(total_paths)))
        print('total_labels : ' + str(len(total_labels)))

        return total_paths, total_labels
Exemplo n.º 5
0
    def get_total_data_path(self, data_dir):
        total_paths, total_labels = [], []  # 이미지 path와 정답(label) 세트를 저장할 list

        image_paths = sorted(list(paths.list_images(data_dir)))
        for image_path in image_paths:
            # a. 이미지 전체 파일 path 저장
            total_paths.append(image_path)
            # b. 이미지 파일 path에서  이미지의 정답(label) 세트 추출
            label = image_path.split(os.path.sep)[-2]
            total_labels.append(label)

        total_labels = np.array(total_labels)
        lb = LabelBinarizer()
        total_labels = lb.fit_transform(total_labels)

        return total_paths, total_labels
    def load_data(dir=dir):
        print("[INFO] 학습할 이미지 로드 (로드시 경로들 무작위로 섞음)")
        imagePaths = sorted(list(paths.list_images(dir)))
        random.seed(42)
        random.shuffle(imagePaths)

        # data()와 labels 초기화
        datas = []  # 이미지 파일을 array 형태로 변환해서 저장할 list
        labels = []  # 해당 이미지의 정답(label) 세트를 저장할 list

        print("[INFO] 모든 이미지에 대하여 이미지 데이터와 라벨을 추출 ..")
        for imagePath in imagePaths:
            #print(imagePath)
            # a. 이미지를 로드하고, 전처리를 한 후 데이터 목록에 저장
            image = cv2.imread(imagePath)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = DataLoader.img_preprocess(image)
            image = img_to_array(image)
            datas.append(image)
            # b. 이미지 파일명에서  이미지의 정답(label) 세트 추출
            label = imagePath.split(os.path.sep)[-2]
            labels.append(label)

        print("[INFO] scale the raw pixel 의 밝기값을 [0, 1]으로 조정하고 np.array로 변경")
        data = np.array(datas, dtype="float") / 255.0
        labels = np.array(labels)

        print("[INFO] data matrix: {} images ({:.2f}MB)".format(
            len(imagePaths), data.nbytes / (1024 * 1000.0)))

        #  훈련 용 데이터의 80 %와 시험용 나머지 20 %를 사용하여 데이터를 훈련 및 테스트 분할로 분할
        (x_train, x_val, y_train, y_val) = train_test_split(data,
                                                            labels,
                                                            test_size=0.2,
                                                            random_state=42)

        lb = LabelBinarizer()
        y_train = lb.fit_transform(y_train)
        y_val = lb.transform(y_val)  # fit_transform??????????

        return x_train, y_train, x_val, y_val, lb
    input_shape = (FLG.DEPTH, FLG.HEIGHT, FLG.WIDTH)

# model = MobileNetBuilder.build_mobilenet_v2(input_shape=input_shape, classes=2)
model = SmallerVGGNet.build(width=FLG.WIDTH, height=FLG.HEIGHT, depth=FLG.DEPTH, classes=2, finalAct="softmax")

h5_weights_path = 'output/backup/smallvgg_defect_padding200_32/modelsaved/h5/smallvgg_defect_padding200_32_weights.h5'
# h5_weights_path = 'output/a_defect_x4_300_32/modelsaved/h5/a_defect_x4_200_32_weights.h5'

model.load_weights(h5_weights_path)
model.compile(loss=categorical_crossentropy, optimizer='rmsprop', metrics=['accuracy'])

datas = []
origs = []

data_dir = 'D:/2. data/iris_pattern/test_image/22'
imagePaths = sorted(list(paths.list_images(data_dir)))

for imagePath in imagePaths:
    image = cv2.imread(imagePath)
    # image = findRegion(image)
    image = img_padding_2(image)
    origs.append(image.copy())
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = img_to_array(image)
    datas.append(image)

data = np.array(datas, dtype="float") / 255.0
predictions = model.predict(data, batch_size=FLG.BATCH_SIZE)

# 그라디언트 클래스 활성화 맵을 초기화하고 히트 맵을 빌드
    def load_data_test_train(data_dir):
        print("[INFO] 학습할 이미지 로드 (로드시 경로들 무작위로 섞음)")
        imagePaths = sorted(list(paths.list_images(data_dir)))
        random.seed(42)
        random.shuffle(imagePaths)

        # data()와 labels 초기화
        datas = []  # 이미지 파일을 array 형태로 변환해서 저장할 list
        defectLabels = []  # 해당 이미지의 정답(label) 세트를 저장할 list
        lacunaLabels = []  # 해당 이미지의 정답(label) 세트를 저장할 list
        spokeLabels = []  # 해당 이미지의 정답(label) 세트를 저장할 list
        spotLabels = []  # 해당 이미지의 정답(label) 세트를 저장할 list

        print("[INFO] 모든 이미지에 대하여 이미지 데이터와 라벨을 추출 ..")
        for imagePath in imagePaths:
            # a. 이미지를 로드하고, 전처리를 한 후 데이터 목록에 저장
            image = cv2.imread(imagePath)
            image = DataLoader.img_preprocess(image)
            image = img_to_array(image)
            datas.append(image)
            # b. 이미지 파일명에서  이미지의 정답(label) 세트 추출
            (defect, lacuna, spoke,
             spot) = imagePath.split(os.path.sep)[-2].split("_")
            defectLabels.append(defect)
            lacunaLabels.append(lacuna)
            spokeLabels.append(spoke)
            spotLabels.append(spot)

        print("[INFO] scale the raw pixel 의 밝기값을 [0, 1]으로 조정하고 np.array로 변경")
        data = np.array(datas, dtype="float") / 255.0
        print("[INFO] data matrix: {} images ({:.2f}MB)".format(
            len(imagePaths), data.nbytes / (1024 * 1000.0)))

        defectLabels = np.array(defectLabels)
        lacunaLabels = np.array(lacunaLabels)
        spokeLabels = np.array(spokeLabels)
        spotLabels = np.array(spotLabels)

        print("[INFO] binarize both sets of labels..")
        defectLB = LabelBinarizer()
        lacunaLB = LabelBinarizer()
        spokeLB = LabelBinarizer()
        spotLB = LabelBinarizer()
        defectLabels = defectLB.fit_transform(defectLabels)
        lacunaLabels = lacunaLB.fit_transform(lacunaLabels)
        spokeLabels = spokeLB.fit_transform(spokeLabels)
        spotLabels = spotLB.fit_transform(spotLabels)

        # loop over each of the possible class labels and show them
        for (i, label) in enumerate(defectLB.classes_):
            print("{}. {}".format(i + 1, label))
            print(defectLB.classes_)
        for (i, label) in enumerate(lacunaLB.classes_):
            print("{}. {}".format(i + 1, label))
            print(lacunaLB.classes_)
        for (i, label) in enumerate(spokeLB.classes_):
            print("{}. {}".format(i + 1, label))
            print(spokeLB.classes_)
        for (i, label) in enumerate(spotLB.classes_):
            print("{}. {}".format(i + 1, label))
            print(spotLB.classes_)

        return data, defectLabels, lacunaLabels, spokeLabels, spotLabels, defectLB, lacunaLB, spokeLB, spotLB
                            classes=FLG.CLASS_NUM,
                            finalAct="softmax")

h5_weights_path = 'output/smallervgg_0721_1400_5_200/model_saved/smallervgg_0721_1400_5_200_weight.h5'

model.load_weights(h5_weights_path)
model.compile(loss=categorical_crossentropy,
              optimizer='rmsprop',
              metrics=['accuracy'])

datas = []
origs = []
src_dir = 'D:/2. data/js_15angle/mask_blue_1'
dst_dir = 'D:/2. data/js_15angle/predicted_mask/'

imagePaths = sorted(list(paths.list_images(src_dir)))
for imagePath in imagePaths:
    image = cv2.imread(imagePath)
    image = cv2.resize(image, (FLG.HEIGHT, FLG.WIDTH))
    origs.append(image.copy())
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = img_to_array(image)
    datas.append(image)

data = np.array(datas, dtype="float") / 255.0
preds = model.predict(data, batch_size=FLG.BATCH_SIZE)

label_lists = ['defect', 'lacuna', 'normal', 'spoke', 'spot']

print(">> move images")
for i, prediction in enumerate(preds):