pythonimageopencvimage-processingimage-editing

How to change black color to Red with OpenCV Python?


How can you make it in Python? I faced a problem with this line

img_rgb.Set(mask,cv2.Scalar(0,0,255))

and here is the code :

import numpy as np
import imutils

import cv2

img_rgb = cv2.imread('figi.jpg')

Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)

img_rgb.Set(mask,cv2.Scalar(0,0,255))

cv2.imshow("imgOriginal", img_rgb)  # show windows

cv2.imshow("output", res)  # show windows

cv2.imshow("mask", mask)  # show windows

cv2.waitKey(0)

Solution

  • The API for mat.setTo() is not available in Opencv module for python, this is due to the reason that in C++ Opencv uses cv::Mat object as basic entity for image manipulation, However in Python there is no such cv::Mat concept, instead Python API for Opencv uses the well known library numpy for image manipulation operations, and numpy has a very beautiful syntax to set the values using a mask:

    img_rgb[mask == 255] = [0, 0, 255]
    

    Simply replacing this line with the img_rgb.Set(mask,cv2.Scalar(0,0,255)) would get your work done.