Ask Your Question

I have an image with all pixel values 0 i.e black image, i want to access pixels at certain image coordinates more then a 100 and change the value to 1 how can i do this using opencv python and for loops if possible?

asked 2018-08-25 08:17:39 -0500

The whole idea is to create a binary image with white pixel values which are defined by user.

edit retag flag offensive close merge delete



what is the purpose of it ? you probably should avoid writing loops, but prefer opencv or numpy functions.

also note, that "binary" images in opencv are [0,255], not [0,1]

do you want to change the position, or the value of the pixels ? (that's a bit unclear here)

berak gravatar imageberak ( 2018-08-25 08:28:15 -0500 )edit
berak gravatar imageberak ( 2018-08-25 08:30:52 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2018-08-28 14:54:46 -0500

MikeTronix gravatar image

Now I agree that you should avoid writing loops in Python, but if I understand your question correctly, you want to have a loop over a precomputed set of array coordinates and set the matching image pixels to 1. Here is a working example using Python which displays using OpenCV. Hope it helps.

import matplotlib.pyplot as plt
import numpy as np
import cv2

def plot_dots(coords,img_h,img_w):
    img = np.zeros((img_h,img_w), dtype=np.uint8)
    for c in range(coords.shape[1]):
        img[coords[0,c],coords[1,c]] = 1
    return img

if __name__ == "__main__":
    numdots = 100
    img_w = 800
    img_h = 600
    xcoords = np.random.randint(0,img_w-1,(numdots,))
    ycoords = np.random.randint(0,img_h-1,(numdots,))
    coords = np.vstack((ycoords,xcoords))
    img = 255 * plot_dots(coords,img_h,img_w)
    cimg = np.dstack((img,img,img))
    dimg = cimg.astype(np.uint8)
    while True:
        cv2.imshow('dots', dimg)
        ch = cv2.waitKey(1)
        if (ch > 0):
edit flag offensive delete link more
Login/Signup to Answer

Question Tools



Asked: 2018-08-25 08:17:39 -0500

Seen: 240 times

Last updated: Aug 28 '18