Firstly, I think you need to check that your lower and upper bound is within the range of 0 to 255.
Secondly, your "temporal" variable is a "mask". It is set to 255 at location (x, y) if the pixel value at that location is within your lower and upper bound. It does not contain all the pixels that lies in the given range.
Below is some code I tried on a test image. Note that I made use of some numpy but converted to CvMat using cv2.cv.fromarray() to match your code.
#!/usr/bin/env python
import cv2
import numpy as np
def main():
image = cv2.imread("forest.jpg")
imageMat = cv2.cv.fromarray(image)
dst = cv2.cv.fromarray(np.zeros((imageMat.rows, imageMat.cols), np.uint8))
x = 250 # Manually set pixel location. You can get this from your mouse event handler.
y = 500
pixel = image[y, x] # Note y index "row" of matrix and x index "col".
tolerance = 10
# Ensure your bounds are within 0 and 255.
lower = tuple(map(lambda x: int(max(0, x - tolerance)), pixel))
upper = tuple(map(lambda x: int(min(255, x + tolerance)), pixel))
# Get mask of all pixels that satisfy range condition and store it in dst.
cv2.cv.InRangeS(imageMat, lower, upper, dst)
mask = np.asarray(dst) # Convert back to numpy array.
cv2.imshow("Mask", mask) # The mask indicating which pixels satisfy range conditions
cv2.imshow("Image", image)
extracted = np.zeros_like(image) # The pixels that satisfy range condition.
extracted[np.where(mask)] = image[np.where(mask)]
cv2.imshow("extracted", extracted)
cv2.waitKey()
if __name__ == "__main__":
main()
And this is the python2 version:
#!/usr/bin/env python
import cv2
import numpy as np
def main():
image = cv2.imread("forest.jpg")
x = 230 # Manually set pixel location. You can get this from your mouse event handler.
y = 300
pixel = image[y, x] # Note y index "row" of matrix and x index "col".
tolerance = 30
# Ensure your bounds are within 0 and 255.
lower = map(lambda x: max(0, x - tolerance), pixel)
upper = map(lambda x: min(255, x + tolerance), pixel)
lower = np.asarray(lower)
upper = np.asarray(upper)
mask = cv2.inRange(image, lower, upper) # Notice we can just get mask without having to allocate it beforehand.
cv2.imshow("Mask", mask) # The mask indicating which pixels satisfy range conditions
cv2.imshow("Image", image)
extracted = np.zeros_like(image) # The pixels that satisfy range condition.
extracted[np.where(mask)] = image[np.where(mask)]
cv2.imshow("extracted", extracted)
cv2.waitKey()
if __name__ == "__main__":
main()