如何使背景清晰

时间:2019-04-02 09:15:53

标签: python image opencv

我有拼图的图像,我正在研究一种匹配拼图的算法。我想在找到每个谜题的匹配项后显示当前结果的图像。 puzzle piece。我想将所有图像粘贴在一个平面上..但是找不到确切的坐标,该图像需要在该坐标上发布以使其与上一块进行匹配。但是似乎找不到使用opencv使背景空白的方法。现在,像素为black(0,0,0)。任何想法,我怎么能使后面的像素空白和过去在不同的图像?

尝试建议的方法后。 enter image description here

上面的图片是我使用这些代码得到的

def show_results(results, puzzle):
    final = Image.new('RGBA', (300 * COL_NUM, 300 * ROW_NUM))
    border = 100
    keys = list(results.keys())
    X, Y = border, border
    x, y = border, border
    for i in keys:
        image = puzzle[results[i]].img
        corners = puzzle[results[i]].corners
        image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2RGBA)
        image[np.all(image == [0, 0, 0, 255], axis=2)] = [0, 0, 0, 0]
        corner0 = corners[0]
        x = X-corner0[0]
        y = Y-corner0[1]
        img = Image.fromarray(np.uint8(image))
        final.paste(img, (x, y))
        corner1 = corners[1]
        X = X + (corner1[0]-corner0[0])
        Y = Y + (corner1[1]-corner0[1])
    final.save('current.png')
    # cv2.imshow("result",final)
    # cv2.waitKey(0)

如何解决此问题。我用于粘贴的格式可能存在问题。但我可以弄清楚

1 个答案:

答案 0 :(得分:1)

我猜您的输入图像默认情况下没有透明背景。 convert_to_png()功能将在您的图片中添加Alpha通道

def convert_to_png(img): 
    fin_img = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA)
    b, g, r, alpha = cv2.split(fin_img)
    alpha[:, :] = 0.0
#    plt.imshow(alpha);plt.title('alpha image');plt.show()     
#    plt.imshow(img);plt.title('original image');plt.show()   
    alpha[np.where((img != (255, 255, 255)).any(axis = 2))] = 255

    fin_img[:,:, 0] = img[:,:,0]
    fin_img[:,:, 1] = img[:,:,1]
    fin_img[:,:, 2] = img[:,:,2]
    fin_img[:,:, 3] = alpha[:,:]

#    plt.imshow(fin_img);plt.title('fin image');plt.show()
    return fin_img

获得带有Alpha通道的图像后,可以像这样将图像彼此粘贴:

y1, y2 = new_loc[1], new_loc[1] + img.shape[0]
x1, x2 = new_loc[0], new_loc[0] + img.shape[1]

alpha_s = img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    fin_img[y1:y2, x1:x2, c] = (alpha_s * img[:, :, c] +
                              alpha_l * img[y1:y2, x1:x2, c])

fin_img是3通道输出图像