import cv2
import cv2 as cv


def access_pixels(frame):
    print(frame.shape)  # shape内包含三个元素：按顺序为高、宽、通道数
    height = frame.shape[0]
    weight = frame.shape[1]
    channels = frame.shape[2]
    print("weight : %s, height : %s, channel : %s" % (weight, height, channels))
    color_black = []
    # 遍历上下
    print("正在遍历上下")
    for row in [0, height - 1]:  # 遍历高
        for col in range(weight):  # 遍历宽
            for color in color_black:
                if isSameColor(color, frame[row, col], 0):
                    break
            else:
                color_black.append(frame[row, col])
    # 遍历左右
    print("正在遍历左右")
    for row in range(height):  # 遍历高
        for col in [0, weight - 1]:  # 遍历宽
            color_black.append(frame[row, col])
    # 遍历所有修改
    print(f"黑名单颜色共计{len(color_black)}个")
    print("正在遍历全部,修改图片结果")
    for row in range(height):  # 遍历高
        for col in range(weight):  # 遍历宽
            color = frame[row, col]
            # 是否符合对比度要求
            baohe = 1 - (min(color) / max(color))
            if baohe < 0.15:
                frame[row, col] = [255, 255, 255]
                continue
            for color_copy in color_black:
                if isSameColor(color, color_copy):
                    frame[row, col] = [255, 255, 255]
                    break

    return frame


def isSameColor(color1, color2, value=3):
    for i in [0, 1, 2]:
        if color1[i] >= color2[i] and color1[i] - color2[i] >= value:
            return False
        if color2[i] >= color1[i] and color2[i] - color1[i] >= value:
            return False
    else:
        return True


src = cv.imread('img2.png')
cv.imshow("test", src)
print("正在处理图片")
frame = access_pixels(src)
print("正在显示图片")
cv.imshow("test", frame)
cv.waitKey(0)
cv2.destroyAllWindows()
