opencv摳圖並對roi區域操作生成新的圖片

 這裏面先使用opencv自帶的圖片進行與操作bitwise_and,就可以得到摳出來的roi區域,然後對mask區域取反bitwise_not,在與原圖片相與得到背景圖片。接下來就可以對摳出來的圖片進行一系列操作,這裏面我做的是減去一個均值。最後將修改後的roi區域,以及背景圖相加就可以得到新的融合後的圖片。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/4/23 23:01
# @Author : caius
# @Site : 
# @File : test.py
# @Software: PyCharm
import matplotlib.pyplot as plt
import cv2
import os, glob
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
id_to_trainid = {1: 1, 2: 1,
                              3: 1, 11: 2, 12: 2, 13: 2, 14:2,255:0}
# id_to_trainid = {1: 1, 2: 1,
#                               3: 1, 11: 1, 12: 1, 13: 1, 14:1,255:0}


mean = 10


def get_palette(num_cls):
    """ Returns the color map for visualizing the segmentation mask.
    Args:
        num_cls: Number of classes
    Returns:
        The color map
    """

    n = num_cls
    palette = [0] * (n * 3)
    for j in range(0, n):
        lab = j
        palette[j * 3 + 0] = 0
        palette[j * 3 + 1] = 0
        palette[j * 3 + 2] = 0
        i = 0
        while lab:
            palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
            palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))
            palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))
            i += 1
            lab >>= 3
    return palette


def id2trainId( label, reverse=False):
    label_copy = label.copy()
    if reverse:
        for v, k in id_to_trainid.items():
            label_copy[label == k] = v
    else:
        for k, v in id_to_trainid.items():
            label_copy[label == k] = v
    return label_copy
image = cv2.imread('./data/img/43.bmp')
label_ = Image.open('./data/label/43_gt.png').convert("L")
label = np.array(label_)
palette = get_palette(25)

label_.putpalette(palette)
label = id2trainId(label)
label = label.astype(np.uint8)
ret,ma1=cv2.threshold(label,0.5,255,cv2.THRESH_BINARY)
roi=cv2.bitwise_and(image,image,mask=ma1)
newroi =  roi- mean
label_not =  cv2.bitwise_not(ma1)
image_xor=cv2.bitwise_and(image,image,mask=label_not)
new_roi = cv2.bitwise_and(newroi,newroi,mask=ma1)
new_image = cv2.add(new_roi,image_xor)
fig1 = plt.figure(figsize=(20, 14))
fig1.add_subplot(2, 3, 1)
plt.imshow(image[:,:,-1::-1])  # # 因爲opencv讀取進來的是bgr順序呢的,而imshow需要的是rgb順序,因此需要先反過來
plt.title("original  image",fontsize=16)
fig1.add_subplot(2, 3, 2)
plt.imshow(roi)
plt.title('roi',fontsize=16)
fig1.add_subplot(2, 3, 3)
plt.imshow(image_xor[:,:,-1::-1])
plt.title('image background',fontsize=16)
fig1.add_subplot(2, 3, 4)
plt.imshow(new_image[:,:,-1::-1])
plt.title('new image',fontsize=16)
fig1.add_subplot(2, 3, 5)
plt.imshow(new_roi)
plt.title('roi - mean value :  {0} '.format(mean),fontsize=16)
fig1.add_subplot(2, 3, 6)
plt.imshow(label_)
plt.title('Label visualization',fontsize=16)


plt.show()
fig1.savefig("result" + str(1) + ".png", dpi=500)

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章