PolarBear10
PolarBear10

Reputation: 2305

How can I make the `cv2.imshow` output the same as the `plt.imshow` output?

How can I make the cv2.imshow output the same as the plt.imshow output?

# loading image
img0 = cv2.imread("image.png")
# converting to gray scale
gray = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY)

# remove noise
img = cv2.GaussianBlur(gray, (3, 3), 0)

# convolute with proper kernels
laplacian = cv2.Laplacian(img, cv2.CV_64F)
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)  # x
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)  # y
imgboth = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0)

plt.imshow(imgboth, cmap='gray')
plt.show()

cv2.imshow("img", cv2.resize(imgboth, (960, 540)))
cv2.waitKey(0)
cv2.destroyAllWindows()
       

original image

enter image description here

plt.output

enter image description here

cv2.imshow

enter image description here

Upvotes: 0

Views: 421

Answers (1)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15387

# ...
canvas = imgboth.astype(np.float32)
canvas /= np.abs(imgboth).max()
canvas += 0.5
cv.namedWindow("canvas", cv.WINDOW_NORMAL)
cv.imshow("canvas", canvas)
cv.waitKey()
cv.destroyWindow("canvas")

canvas

only looks different because you posted thumbnails, not the original size image.

when you give imshow floating point values, which you do because laplacian and sobelx are floating point, then it assumes a range of 0.0 .. 1.0 as black .. white.

matplotlib automatically scales data. OpenCV's imshow doesn't. both behaviors have pros and cons.

Upvotes: 2

Related Questions