1

I tried to detect edges of an image. For that, I wrote the following code:

import numpy as np
import cv2
import math
img = cv2.imread('download.jpg',0)
img1 = img
k = img.shape
i=1
x=k[0]
y=k[1]
print x,y
while(i<(x-2)):
    j=1
    while(j<(y-2)):
        a = (int(img[i,j+1])-int(img[i,j]))
        b = (int(img[i+1,j])-int(img[i,j]))
        c = (a**2) + (b**2)
        img1[i,j] = math.sqrt(c)
        #img1[i,j] = a
        j+=1
    i+=1
i=1
print "img"
print img
print "img1"
print img1
print i,j
cv2.imshow("image1",img1)
cv2.imshow("image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

No where in the code img is modified. Yet, at the end of the code, the pixel values of img are changed(which are same as img1). Can anybody explain me what Iam missing?

2
  • perform deep copy.. i.e. img1=img.clone(); instead of assignment. Commented May 20, 2015 at 4:57
  • Is not the key of the question, but your "edge detection" is simply the gradient magnitude. You can compute that faster using numpy as: dy, dx = np.gradient(img); magnitude = np.sqrt(dy**2 + dx**2)). Commented May 20, 2015 at 13:10

1 Answer 1

1

Reason is, assignment statements in Python do not copy objects, after you did img1 = img, img and img1 still point to the same Image object, you need to make a copy if you need to mutate the objects independently

You can also simply instantiate two Image objects

img = cv2.imread('download.jpg', 0)
img1 = cv2.imread('download.jpg', 0)

Otherwise you'll need to copy the python object img, e.g. using https://docs.python.org/2/library/copy.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.