"Mozart, Beethoven, and Chopin never died. They simply became music."
康威生命游戏规则十分简单,简化后如下:
一个“细胞”(或者说单元)分为生或死两种状态,
如果活相邻细胞有2或3个活细胞 该细胞活,否则死
如果死细胞周围有3个活细胞,该细胞转为活。
再OpenCV中,将二值化图像数值变为0和1之后,使用该内核进行卷积核操作(个位储存相邻活细胞个数,十位储存中间细胞生或死状态)
threshed_value = (convolved/255).astype(np.uint8)
kernel = np.asarray([[1,1,1],
[1,10,1],
[1,1,1]],dtype='uint8')
需要注意的是进行卷积操作的时候需要设置边界类型,这里将图像边界作为0处理
接下来对图片进行几次掩膜操作,完成一个循环
convolved = cv.filter2D(src=threshed_value, ddepth=cv.CV_8U,
kernel=kernel,borderType=cv.BORDER_CONSTANT)
#populated:
convolved[convolved==10] = 0 #单独死亡
convolved[convolved==11] = 0
convolved[convolved>=14] = 0
#unpopulated:
convolved[convolved==3] = 255 #复活细胞
#binarize again
convolved[convolved>10] = 255 #转化为常值
convolved[convolved<10] = 0
#重新将图像数据转化成0和1
ret,threshed_value = cv.threshold(convolved,10,1,cv.THRESH_BINARY)
整个代码见下
import cv2 as cv
import numpy as np
image = cv.imread('John_H_Conway_2005_(cropped).jpg',0)
convolved = cv.adaptiveThreshold(image,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv.THRESH_BINARY,11,5)
threshed_value = (convolved/255).astype(np.uint8)
kernel = np.asarray([[1,1,1],
[1,10,1],
[1,1,1]],dtype='uint8')
for name in ['convolved']:
cv.namedWindow(name,cv.WINDOW_NORMAL)
cv.imshow(name,eval(name))
key = cv.waitKey(0)
mode = True
while True:
cv.imshow('convolved',convolved)
key = cv.waitKey(10)
if key == 27:
break
convolved = cv.filter2D(src=threshed_value, ddepth=cv.CV_8U, kernel=kernel,borderType=cv.BORDER_CONSTANT)
#populated:
convolved[convolved==10] = 0 #solitude
convolved[convolved==11] = 0
convolved[convolved>=14] = 0
#unpopulated:
convolved[convolved==3] = 255 #revived
#binarize again
convolved[convolved>10] = 255
convolved[convolved<10] = 0
ret,threshed_value = cv.threshold(convolved,10,1,cv.THRESH_BINARY)