Emre BEGEN
Emre BEGEN

Reputation: 597

How to use Pytorch Tensor object in Opencv without convert to numpy array?

I’m trying to develop a text detection application with Pytorch and Opencv in Python. I can use Pytorch tensor with Opencv like below.

val = y[0,:,:,0].data.cpu().numpy()
cv2.threshold(val , 0.4, 1, 0)

But it takes a lot of time. I need to do this operation by using the tensor object. How can I do that?

Upvotes: 1

Views: 1606

Answers (1)

Berriel
Berriel

Reputation: 13601

Given that the last 0 in your threshold call means cv.THRESH_BINARY, it follows this function:

enter image description here

As your maxval is set to 1, you can replace this threshold call with something like this:

(y[0,:,:,0] > 0.4).float()

I am casting to float, but you can change that as you wish, ofc. Or even to something like:

(y[0,:,:,0] > 0.4).to(dtype=y.dtype)

so that it will remain with the same data type.

Upvotes: 4

Related Questions