简体   繁体   中英

How to change specific pixel value in grayscale image?

I want to change the pixel value of a grayscale image using OpenCV.

Assume that I have a grayscale image and I want to convert all its pixel to 0 value one at a time. So that the resultant image is completely black. I tried this but there is no change in the image:

image = cv2.imread('test_image.png',0)

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        image[i, j] = 0

Result:

display the updated image

In most cases, you want to avoid using double for loops to modify pixel values since it is very slow. A better approach is to use Numpy for pixel modification since OpenCV uses Numpy arrays to display images. To achieve your desired result, you can use np.zeros to create a completely black image with the same shape as the original image.

import cv2
import numpy as np

image = cv2.imread("test_image.png", 0)

black = np.zeros(image.shape, np.uint8)

cv2.imshow('image', image)
cv2.imshow('black', black)
cv2.waitKey(0)

For example with a test image. Original (left), result (right)

I would suggest you to always try manipulating the copy of an image so that the image doesn't get affected in the wrong way. Coming to your question, you can do the following:

import cv2

image = cv2.imread('test_image.png',0)

#Creating a copy of the image to confirm right operation is performed on the image.
image_copy = image.copy() 
image_copy[:,:] = [0] #Setting all values to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM