Jeremy
Jeremy

Reputation: 199

Python OpenCV: Reading an image along x and y axis

Aim: I am trying to read the first point (non-zero) here in this image (shown as the red arrow)

enter image description here

from __future__ import division
import numpy as np

import cv2
im1 = cv2.imread('C:/Users/Desktop/Line.png', 0)
for x in range(0, im1.shape[0], 1):
    for y in range(0, im1.shape[1], 1):
        cpt = im1[x][y]
        if 0 < cpt <= 255 :
           print("This is the value", x,y)

But, the point being printed is this (a zero point):

enter image description here

How is this so?

The original image:

enter image description here

Upvotes: 2

Views: 4334

Answers (1)

Kinght 金
Kinght 金

Reputation: 18341

If your image is clean(without noise), then try this:

import cv2
import numpy as np
img = cv2.imread("JKNp9.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ys,xs = np.nonzero(gray)
idx = np.argsort(xs)[0]

pt = xs[idx], ys[idx]

print(pt)
cv2.line(img, pt, pt, (0,255,0), 3, cv2.LINE_AA)
cv2.imshow("img", img)
cv2.waitKey()

The pt is: (27, 388)

This's it:

enter image description here

Upvotes: 1

Related Questions