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?

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

edit retag close merge delete

## Comments

1

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)

1

## 1 answer

Sort by » oldest newest most voted

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):
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):
break
cv2.destroyAllWindows()

more

Official site

GitHub

Wiki

Documentation

## Stats

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

Seen: 815 times

Last updated: Aug 28 '18