画像の一部色変更(OpenCV)

色変更カスタム

できたもの

before
f:id:shibi_rr:20211227102048j:plain
after
f:id:shibi_rr:20211227102109j:plain

###########
gif
f:id:shibi_rr:20211227105853g:plain
###########

コード

核の部分だけ

def trans_color(img_in ,after_color, hmin , hmax , smin, smax ,vmin , vmax ):
    im_trim = img_in.copy()

    #            範囲   0 ≤ H ≤ 179、0 ≤ S ≤ 255、0 ≤ V ≤ 255 
    it1 = ext_red_B_R(im_trim , hmin , hmax  , smin , smax , vmin ,  vmax  )

    mask = cv2.cvtColor( it1  , cv2.COLOR_BGR2GRAY)
    prnim_gray(mask)
    mask = np.where(mask == 255 , 0 , 1 )
    mask = (mask).astype(np.uint16)

    im_trim16 = (im_trim).astype(np.uint16)

    im_trim16[:,:,0] = np.where(im_trim16[:,:,0] == 0 , 256 , im_trim16[:,:,0] )
    im_trim16[:,:,1] = np.where(im_trim16[:,:,1] == 0 , 256 , im_trim16[:,:,1] )
    im_trim16[:,:,2] = np.where(im_trim16[:,:,2] == 0 , 256 , im_trim16[:,:,2] )

    im_trim16[:,:,0] = im_trim16[:,:,0] * mask
    im_trim16[:,:,1] = im_trim16[:,:,1] * mask
    im_trim16[:,:,2] = im_trim16[:,:,2] * mask

    im_trim16[:,:,0] = np.where(im_trim16[:,:,0] == 0 , after_color[2] , im_trim16[:,:,0] )
    im_trim16[:,:,1] = np.where(im_trim16[:,:,1] == 0 , after_color[1] , im_trim16[:,:,1] )
    im_trim16[:,:,2] = np.where(im_trim16[:,:,2] == 0 , after_color[0] , im_trim16[:,:,2] )

    im_trim16[:,:,0] = np.where(im_trim16[:,:,0] == 0 , after_color[2] , im_trim16[:,:,0] )
    im_trim16[:,:,1] = np.where(im_trim16[:,:,1] == 0 , after_color[1] , im_trim16[:,:,1] )
    im_trim16[:,:,2] = np.where(im_trim16[:,:,2] == 0 , after_color[0] , im_trim16[:,:,2] )

    im_trim16[:,:,0] = np.where(im_trim16[:,:,0] == 256 , 0 , im_trim16[:,:,0] )
    im_trim16[:,:,1] = np.where(im_trim16[:,:,1] == 256 , 0 , im_trim16[:,:,1] )
    im_trim16[:,:,2] = np.where(im_trim16[:,:,2] == 256 , 0 , im_trim16[:,:,2] )


    im_trim = (im_trim16).astype(np.uint8)
    return im_trim

プログラムの流れ

f:id:shibi_rr:20211227111503p:plain
元画像
===========================
f:id:shibi_rr:20211227111542p:plain
トリミングした画像
===========================
f:id:shibi_rr:20211227111635p:plain
変更前の部分だけを白にする
===========================
f:id:shibi_rr:20211227111713p:plain
白の部分を任意の色にする
===========================
f:id:shibi_rr:20211227111759p:plain
元の画像と合成する