# 横向 flag = False for i inrange(img.shape[0]): for j inrange(img.shape[1]): if img[i][j] == 255: flag = not flag while img[i][j] == 255: j += 1 if j >= img.shape[1]: break if j >= img.shape[1]: break if flag == True: img1[i][j] = 255 flag = False cv2.imshow("1", img1) # 纵向 flag = False for i inrange(img.shape[1]): for j inrange(img.shape[0]): if img[j][i] == 255: flag = not flag while img[j][i] == 255: j += 1 if j >= img.shape[0]: break if j >= img.shape[0]: break if flag == True: img2[j][i] = 255 flag = False cv2.imshow("2", img2) img = img1 & img2 # cv2.imshow("3", img) cv2.waitKey(0) return img