1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
import cv2 as cv import numpy as np
def get_qufendu(array): qufendu = np.zeros((2, 2)) result = np.zeros((2, 2)) for i in range(2): for j in range(2): qufendu[i][j] = max(array[i][j], array[i+1][j], array[i+1][j+1], array[i][j+1]) - min(array[i][j], array[i+1][j], array[i+1][j+1], array[i][j+1]) if qufendu[i][j] > 40: result[i][j] = 1 return result
def classify_array(array): a_sum = array[0][0] + array[0][1] + array[1][1] + array[1][0] if a_sum == 0 or a_sum == 4: return 0 elif a_sum == 1 or a_sum == 3: return 1 elif a_sum == 2: if array[0][0] == array[0][1]: return 2 else: return 3
def get_channel_flag(channel, channel_flag, k): row, col, cnt_channel = channel.shape for i in range(row-2): for j in range(col-2): array33 = np.zeros((3, 3)) for x in range(3): for y in range(3): array33[x][y] = channel[i+x][j+y][k] array_flag = get_qufendu(array33) channel_flag[i+1][j+1][k] = classify_array(array_flag) return channel, channel_flag
def get_flag(img): flag = np.zeros(img.shape) row, col, cnt_channel = img.shape for k in range(cnt_channel): img, flag = get_channel_flag(img, flag, k) return flag
def get_value(pixel, flag): if flag == 1: pixel[0] = 255 pixel[1] = 0 pixel[2] = 0 elif flag == 2: pixel[0] = 0 pixel[1] = 255 pixel[2] = 0 elif flag == 3: pixel[0] = 0 pixel[1] = 0 pixel[2] = 255 else: pixel[0] = 255 pixel[1] = 255 pixel[2] = 255 return pixel
def mark(img, flag): row, col, cnt_channel = img.shape for i in range(row): for j in range(col): if flag[i][j][0] == flag[i][j][1] and flag[i][j][1] == flag[i][j][2]: img[i][j] = get_value(img[i][j], flag[i][j][0]) return img
def main(img): p = cv.imread(img, 1) b, g, r = cv.split(p) flag = get_flag(p) p = mark(p, flag) cv.imwrite('mark_' + img, p)
if __name__ == '__main__': img_addr = '8068.jpg' main(img_addr)
|