本文介绍了Python numpy减法没有负数(4-6给出254)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望彼此减去2张灰色人脸以查看差异,但是我遇到了一个问题,例如减去[4]-[6]给出的是[254],而不是[-2](或区别为[2]).

I wish to subtract 2 gray human faces from each other to see the difference, but I encounter a problem that subtracting e.g. [4] - [6] gives [254] instead of [-2] (or difference: [2]).

print(type(face)) #<type 'numpy.ndarray'>
print(face.shape) #(270, 270)
print(type(nface)) #<type 'numpy.ndarray'>
print(nface.shape) #(270, 270)

#This is what I want to do:
sface = face - self.nface #or
sface = np.subtract(face, self.nface)

两者都不给出负数,而是从255中减去0后的其余部分.

Both don't give negative numbers but instead subtract the rest after 0 from 255.

sface的输出示例:

Output example of sface:

[[  8 255   8 ...,   0 252   3]
 [ 24  18  14 ..., 255 254 254]
 [ 12  12  12 ...,   0   2 254]
 ..., 
 [245 245 251 ..., 160 163 176]
 [249 249 252 ..., 157 163 172]
 [253 251 247 ..., 155 159 173]]

我的问题:在减去人脸和nface中每个点的差后,如何使sface成为具有负值的numpy.ndarray(270,270)? (因此不是numpy.setdiff1d,因为它仅返回1个尺寸,而不是270x270)

My question:How do I get sface to be an numpy.ndarray (270,270) with either negative values after subtracting or the difference between each point in face and nface? (So not numpy.setdiff1d, because this returns only 1 dimension instead of 270x270)

从@ajcr的答案中,我做了以下操作(abs()用于显示减去的脸):

From the answer of @ajcr I did the following (abs() for showing subtracted face):

face_16 = face.astype(np.int16)
nface_16 = nface.astype(np.int16)
sface_16 = np.subtract(face_16, nface_16)
sface_16 = abs(sface_16)
sface = sface_16.astype(np.int8)

推荐答案

听起来数组的dtypeuint8.所有数字将被解释为0-255范围内的整数.在这里-2等于256-2,因此相减得出254.

It sounds like the dtype of the array is uint8. All the numbers will be interpreted as integers in the range 0-255. Here, -2 is equal to 256 - 2, hence the subtraction results in 254.

您需要将数组重铸为支持负整数的dtype,例如int16像这样...

You need to recast the arrays to a dtype which supports negative integers, e.g. int16 like this ...

face = face.astype(np.int16)

...然后减去.

这篇关于Python numpy减法没有负数(4-6给出254)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 00:45