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
| import cv2 as cv import numpy as np import matplotlib.pyplot as plt
def Division_Judge(img, h0, w0, h, w) : area = img[h0 : h0 + h, w0 : w0 + w] mean = np.mean(area) std = np.std(area, ddof = 1)
total_points = 0 operated_points = 0
for row in range(area.shape[0]) : for col in range(area.shape[1]) : if (area[row][col] - mean) < 2 * std : operated_points += 1 total_points += 1
if operated_points / total_points >= 0.95 : return True else : return False
def Merge(img, h0, w0, h, w) : for row in range(h0, h0 + h) : for col in range(w0, w0 + w) : if img[row, col] > 100 and img[row, col] < 200: img[row, col] = 0 else : img[row, col] = 255
def Recursion(img, h0, w0, h, w) : if not Division_Judge(img, h0, w0, h, w) and min(h, w) > 5 : Division_Judge(img, h0, w0, int(h0 / 2), int(w0 / 2)) Division_Judge(img, h0, w0 + int(w0 / 2), int(h0 / 2), int(w0 / 2)) Division_Judge(img, h0 + int(h0 / 2), w0, int(h0 / 2), int(w0 / 2)) Division_Judge(img, h0 + int(h0 / 2), w0 + int(w0 / 2), int(h0 / 2), int(w0 / 2)) else : Merge(img, h0, w0, h, w)
def Division_Merge_Segmented() : img = cv.imread('images/shapes.png') img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) hist, bins = np.histogram(img_gray, bins = 256) print(f'五角星、椭圆、背景、五边形的像素值分别为:' f'{"、".join("%s" % pixel for pixel in np.unique(img_gray))}')
segemented_img = img_gray.copy() Recursion(segemented_img, 0, 0, segemented_img.shape[0], segemented_img.shape[1])
plt.figure(figsize=(12, 4)) plt.subplot(131), plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)) plt.axis('off'), plt.title(f'$input\_image$') plt.subplot(132), plt.imshow(img_gray, cmap='gray', vmin = 0, vmax = 255) plt.axis('off'), plt.title(f'$gray\_image$') plt.subplot(133), plt.imshow(segemented_img, cmap='gray') plt.axis('off'), plt.title(f'$segmented\_image$') plt.tight_layout() plt.show()
if __name__ == '__main__': Division_Merge_Segmented()
|