np.zeros_like如何指定0为整数类型
时间: 2024-05-11 10:13:39 浏览: 8
可以使用dtype参数来指定数据类型,例如:
```python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
zeros_arr = np.zeros_like(arr, dtype=int)
print(zeros_arr)
```
输出结果为:
```
[[0 0 0]
[0 0 0]]
```
在上面的代码中,使用dtype=int来指定数据类型为整数类型。
相关问题
Traceback (most recent call last): File "D:\PycharmProjects\老照片修复复杂\main.py", line 81, in <module> main() File "D:\PycharmProjects\老照片修复复杂\main.py", line 71, in main missing = extract_missing(img, edges) File "D:\PycharmProjects\老照片修复复杂\main.py", line 41, in extract_missing missing = cv2.bitwise_and(img, img, mask=cv2.drawContours(np.zeros_like(img), [hull], 0, (255, 255, 255), -1)) cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\core\src\arithm.cpp:230: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'
这个错误提示是OpenCV抛出的。根据错误提示,它似乎是由于掩码(mask)的数据类型不正确引起的。在你的代码中,你正在使用np.zeros_like()函数创建一个全零数组作为掩码,并且尝试将其与图像进行按位与运算。但是,由于你没有指定数据类型,np.zeros_like()函数默认使用与输入数组相同的数据类型,这可能会导致错误。你可以尝试将掩码的数据类型设置为np.uint8,例如:
```
missing = cv2.bitwise_and(img, img, mask=cv2.drawContours(np.zeros_like(img, dtype=np.uint8), [hull], 0, (255, 255, 255), -1))
```
这样,你可以将掩码的数据类型设置为8位无符号整数类型,避免了上述错误。
gray_fft = np.fft.fft2(gray) gray_fftshift = np.fft.fftshift(gray_fft) dst_fftshift = np.zeros_like(gray_fftshift) M, N = np.meshgrid(np.arange(-cols // 2, cols // 2), np.arange(-rows // 2, rows // 2)) D = np.sqrt(M ** 2 + N ** 2) Z = (rh - r1) * (1 - np.exp(-c * (D ** 2 / d0 ** 2))) + r1 dst_fftshift = Z * gray_fftshift dst_fftshift = (h - l) * dst_fftshift + l dst_ifftshift = np.fft.ifftshift(dst_fftshift) dst_ifft = np.fft.ifft2(dst_ifftshift) dst = np.real(dst_ifft) dst = np.uint8(np.clip(dst, 0, 255)) return dst
在这个函数中,首先使用np.fft.fft2函数将输入图像进行二维傅里叶变换,然后使用np.fft.fftshift函数将变换结果进行中心化处理。接下来,创建一个与输入图像大小相同的全零数组dst_fftshift,并计算出输入图像的行数和列数。
函数接着使用np.meshgrid函数生成网格坐标,并根据频率域滤波器的公式计算出增益系数Z。然后,将增益系数Z乘以中心化的傅里叶变换结果gray_fftshift,得到增益后的频率域图像dst_fftshift。
接着,将增益后的频率域图像dst_fftshift乘以(h - l),再加上l,得到最终的频率域图像。然后,使用np.fft.ifftshift函数将频率域图像逆中心化,并使用np.fft.ifft2函数将其转换回空间域。最后,将输出图像进行限幅处理,转换为8位无符号整数类型,然后返回输出图像。