I want to load a color image, convert it to grayscale, and then invert the data in the file.
What I need: to iterate over the array in OpenCV and change every single value with this formula (it might be wrong but it seems reasonable for me):
img[x,y] = abs(img[x,y] - 255)
but I don't understand why doesn't it works:
def inverte(imagem, name): imagem = abs(imagem - 255) cv2.imwrite(name, imagem) def inverte2(imagem, name): for x in np.nditer(imagem, op_flags=['readwrite']): x = abs(x - 255) cv2.imwrite(name, imagem) if __name__ == '__main__': nome = str(sys.argv[1]) image = cv2.imread(nome) gs_imagem = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) inverte(gs_imagem, "invertida.png") inverte2(gs_imagem, "invertida2.png")
I don't want to do an explicit loop (I am trying to be more pythonic). I can see that in one image that got a white background it turned black, but only this it doesn't looks like the other colors are having much (if any) change.
OpenCV-Python is a library of programming functions mainly aimed at real-time computer vision. cv2. flip() method is used to flip a 2D array. The function cv::flip flips a 2D array around vertical, horizontal, or both axes.
In cv2. flip() argument try using 0 if you want to flip in y axis, 1 if you want to flip in x axis and -1 if want to flip in both axes.
If you have a binary image binImage with just zeroes and ones, there are a number of simple ways to invert it: binImage = ~binImage; binImage = 1-binImage; binImage = (binImage == 0); Then just save the inverted image using the function IMWRITE.
You almost did it. You were tricked by the fact that abs(imagem-255)
will give a wrong result since your dtype
is an unsigned integer. You have to do (255-imagem)
in order to keep the integers unsigned:
def inverte(imagem, name): imagem = (255-imagem) cv2.imwrite(name, imagem)
You can also invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With