Tensorflow equivalent for cv2.addWeighted?


Is there a TensorFlow equivalent for cv2.addWeighted()? I need this function for image processing on my tf.dataset object.

If there isn’t, how can I use the OpenCV method with TensorFlow to get the same result?

Here is my code below for reference.

import tensorflow as tf
from tensorflow.image import ResizeMethod
import pathlib
import os
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import cv2
from PIL import Image

filepaths = df['filepath'].values
labels = df[[0,2,4]].values

ds_train = tf.data.Dataset.from_tensor_slices((filepaths, labels))

def read_image(image_file, labels):
    img = tf.io.read_file(image_file)
    img = tf.image.decode_png(img, channels=3, dtype=tf.uint8)

    img = tf.image.resize(img, [512, 512], preserve_aspect_ratio=False)
    img2 = ...
    # Need something equivalent to cv2.addWeighted() to use on img and img2
    return img, labels

ds_train = ds_train.map(read_image).batch(32, drop_remainder = True)

I apologize in advance if this question has already been answered. I searched everywhere and could not find a way to replicate this.


I think I may have found a work-around by using other tensorflow functions.

import tensorflow as tf
import tensorflow_addons as tfa
def tensorflow_addWeighted(img1, img2):
     img = img1 * tf.multiply(tf.ones(image1_shape, dtype = tf.uint8), alpha) + img2 * tf.multiply(tf.ones(image2_shape, dtype = tf.uint8), beta) + lambda
     return img

This is the same formula in the OpenCV docs, implemented with tensorflow. Alpha, beta, and lambda are the corresponding weight values as you would use them in OpenCV.

Answered By – Manan Vij

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published