Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Maintain by FancyKing
- # Created 1621712715
- # Assuming that the position of the image (0,0) is black,
- # solve for the data of the percentage of black blocks in the white closed area.
- from collections import deque
- import cv2
- import numpy as np
- import threading
- # global pool START
- blk_size_t = 0
- blk_size_flag = False
- wit_size_t = 0
- wit_size_flag = False
- # global pool END
- def black_square(img):
- # use global var
- global blk_size_t, blk_size_flag
- neighbors = deque([(0, 0)])
- flag = np.zeros((img.shape[0], img.shape[1]), dtype=np.int)
- blk_area = 0
- while neighbors:
- row, col = neighbors.popleft()
- flag[row][col] = 1
- blk_area = blk_area + 1
- for x, y in [
- (row - 1, col), (row, col - 1), (row + 1, col), (row, col + 1),
- (row + 1, col + 1), (row + 1, col - 1),
- (row - 1, col + 1), (row - 1, col - 1)
- ]:
- if 0 <= x < img.shape[0] and 0 <= y < img.shape[1] \
- and flag[x][y] == 0 and img[x][y][0] == 0:
- neighbors.append((x, y))
- flag[x][y] = 1
- blk_size_t = blk_area
- blk_size_flag = True
- return blk_area
- def get_white_pix_num(img):
- # use global var
- global wit_size_t, wit_size_flag
- nums = 0
- for line in img:
- for cow in line:
- if cow[0] == 255:
- nums = nums + 1
- wit_size_t = nums
- wit_size_flag = True
- return nums
- def get_pure_img(img):
- return cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]
- def get_img(dir):
- return cv2.imread(dir, cv2.COLOR_BGR2GRAY)
- def show_img(img):
- cv2.namedWindow('pure')
- cv2.imshow('pure', img)
- cv2.waitKey(0)
- def scan_lines(img):
- into_white = False
- all_line_black_num = 0
- sub_line_black_num = 0
- for line in img:
- for pix in line:
- if pix[0] == 0:
- into_white = True
- elif pix[0] == 255:
- if into_white:
- sub_line_black_num = sub_line_black_num + 1
- if into_white:
- all_line_black_num = all_line_black_num + sub_line_black_num
- sub_line_black_num = 0
- into_white = False
- return all_line_black_num
- if __name__ == '__main__':
- # use global var
- imgs = ['T.jpg']
- for item in imgs:
- origin_img = get_img(item)
- pure_img = get_pure_img(origin_img)
- pure_img = cv2.resize(pure_img, [pure_img.shape[1] * 2, pure_img.shape[0] * 2])
- t_b = threading.Thread(target=black_square, args=(pure_img,))
- t_b.setDaemon(True)
- t_b.start()
- t_w = threading.Thread(target=get_white_pix_num, args=(pure_img,))
- t_w.setDaemon(True)
- t_w.start()
- t_b.join()
- t_w.join()
- image_size = pure_img.shape[0] * pure_img.shape[1]
- black_size, white_size = 0, 0
- while blk_size_flag:
- black_size = blk_size_t
- break
- while wit_size_flag:
- white_size = wit_size_t
- break
- print('image size:', image_size)
- print('black areas:', black_size)
- print('white areas:', white_size)
- print('Answer:', (image_size - black_size - white_size) / white_size)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement