def generate_chain_code(image):
image = np.dstack([image, image, image])
img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
_, img_bin = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
row, col = img_bin.shape
if np.all(img_bin == 0):
img_bin[np.random.randint(0, row, 2), np.random.randint(0, col, 2)] = 255
contours, _ = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
chain_code = []
point = contours[0][0][0]
for i in range(1, len(contours[0])):
next_point = contours[0][i][0]
diff = next_point - point
if diff[0] == 0 and diff[1] == 1:
chain_code.append(6)
elif diff[0] == -1 and diff[1] == 1:
chain_code.append(5)
elif diff[0] == -1 and diff[1] == 0:
chain_code.append(4)
elif diff[0] == -1 and diff[1] == -1:
chain_code.append(3)
elif diff[0] == 0 and diff[1] == -1:
chain_code.append(2)
elif diff[0] == 1 and diff[1] == -1:
chain_code.append(1)
elif diff[0] == 1 and diff[1] == 0:
chain_code.append(0)
elif diff[0] == 1 and diff[1] == 1:
chain_code.append(7)
point = next_point
return chain_code