1

I'm using OpenCV/Python and I'm trying to add a number to image.

My code is:

import cv2
import numpy as np
import math
from matplotlib import pyplot as plt

img = cv2.imread('messi.jpg',0)
img2 = img
img2 = cv2.add(img2, np.uint8([50]))

I got the next error:

OpenCV Error: Assertion failed (type2 == CV_64F && (sz2.height == 1 || sz2.heigh
t == 4)) in cv::arithm_op, file C:\builds\master_PackSlaveAddon-win64-vc12-stati
c\opencv\modules\core\src\arithm.cpp, line 1989
Traceback (most recent call last):
  File "lab3_examples.py", line 27, in <module>
    img2 = cv2.add(img, np.uint8([50]))
cv2.error: C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\core
\src\arithm.cpp:1989: error: (-215) type2 == CV_64F && (sz2.height == 1 || sz2.h
eight == 4) in function cv::arithm_op

The image I'm using is messi.jpg enter image description here

Instead, if I use img2 = np.add(img2, np.uint8([50])) intensities that pass the value 255 the value % 255 result, e.g. 260%255=4 the pixel's value is set to 4 instead of 255. As a result, white pixels are turned to black!

Here is the faulty resulted image. enter image description here

Any ideas please?

zinon
  • 4,427
  • 14
  • 70
  • 112

2 Answers2

1

In C++ for this purpose saturate_cast(...) is used. In Python simply

img2 = cv2.add(img2, 50)

will do, if you want to increase brightness for gray-scale image. If implied to colored, color balance will be shifted. For colored image, to save the balance, good answer is by Alex, Bill Grates:

How to fast change image brightness with python + OpenCV?

The only remark - next part of code are not nessessary:

v[v > 255] = 255

v[v < 0] = 0 in my case (Python3,Opencv4).

Andyrey
  • 81
  • 6
0

I would suggest convert the BGR image to HSV image:

hsv= cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

Then split the channels using:

h_channel, s_channel, v_channel = cv2.split(hsv)

Now play with the h_channel:

h_channel + = 20  #---You can try any other value as well---

Now merge the channels back together again:

merged = cv2.merge((h_channel , s_channel , v_channel ))

Finally convert the image back to BGR and display it:

Final_image = cv2.cvtColor(merged, cv2.COLOR_HSV2BGR)
cv2.imshow('Final output', Final_image)

You will see an enhanced or a dimmed image depending on the value you add.

Hope it helps.... :D

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
  • 1
    This a good example, but I want to explain to my students the `RGB` channels so there is no need to involve them with `HSV`. Thank you anyway! – zinon Mar 29 '17 at 10:49
  • In that case, you can try out the same case using RGB image. Split the image to separate channels and add an integer to it merge the channels and then see the result ...Simple .. :D – Jeru Luke Mar 29 '17 at 12:31