import os
import random
import numpy as np
import torch
# define
def fix_rand(seed=2021):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ["PYTHONHASHSEED"] = str(seed)
torch.use_deterministic_algorithms(False)
# torch.use_deterministic_algorithms(True)
def RemoveSmallRegion(Src, Dst, AreaLimit, CheckMode, NeihborMode):
RemoveCount = 0
PointLabel = np.zeros((Src.shape), np.uint8)
if CheckMode == 1: # mode1 小さい領域(白飛び)の削除
for i in range(0, Src.shape[0]):
for j in range(0, Src.shape[1]):
if Src[i][j] < 128:
PointLabel[i][j] = 3
else: # mode0 穴(黒飛び)の削除
for i in range(0, Src.shape[0]):
for j in range(0, Src.shape[1]):
if Src[i][j] >= 128:
PointLabel[i][j] = 3
NeihborPos = list()
NeihborPos.append([-1, 0])
NeihborPos.append([1, 0])
NeihborPos.append([0, -1])
NeihborPos.append([0, 1])
if NeihborMode == 1:
NeihborPos.append([-1, -1])
NeihborPos.append([-1, 1])
NeihborPos.append([1, -1])
NeihborPos.append([1, 1])
NeihborCount = 4 + 4 * NeihborMode
CurrX = 0
CurrY = 0
for i in range(0, Src.shape[0]):
for j in range(0, Src.shape[1]):
if PointLabel[i][j] == 0:
GrowBuffer = list()
GrowBuffer.append([i, j])
PointLabel[i][j] = 1
CheckResult = 0
z = 0
while z < len(GrowBuffer):
for q in range(0, NeihborCount):
CurrY = GrowBuffer[z][0] + NeihborPos[q][0]
CurrX = GrowBuffer[z][1] + NeihborPos[q][1]
if CurrX >= 0 and CurrX < Src.shape[1] and CurrY >= 0 and CurrY < Src.shape[0]:
if PointLabel[CurrY][CurrX] == 0:
GrowBuffer.append([CurrY, CurrX])
PointLabel[CurrY][CurrX] = 1
z = z + 1
if len(GrowBuffer) > AreaLimit:
CheckResult = 2
else:
CheckResult = 1
RemoveCount = RemoveCount + 1
for z in range(0, len(GrowBuffer)):
CurrX = GrowBuffer[z][1]
CurrY = GrowBuffer[z][0]
PointLabel[CurrY][CurrX] += CheckResult
CheckMode = 255 * (1 - CheckMode)
for i in range(0, Src.shape[0]):
for j in range(0, Src.shape[1]):
if PointLabel[i][j] == 2:
Dst[i][j] = CheckMode
elif PointLabel[i][j] == 3:
Dst[i][j] = Src[i][j]