怎么把normalized_beat_2d[i] = np.reshape(normalized_beat[i], (-1, 1))改成转换为2列的二维数组且第二列数据是归一化到-1,1元素序数
时间: 2023-12-10 19:41:42 浏览: 71
可以将代码改为如下形式:
```
normalized_beat_2d = np.zeros((len(normalized_beat), 2))
for i in range(len(normalized_beat)):
normalized_beat_2d[i, 0] = normalized_beat[i]
normalized_beat_2d[i, 1] = (i / (len(normalized_beat) - 1)) * 2 - 1
```
这里我们先创建一个形状为 (len(normalized_beat), 2) 的全零数组 `normalized_beat_2d`,然后使用循环遍历 `normalized_beat` 中的每个元素。对于每个元素,我们把它放到 `normalized_beat_2d` 的第一列,然后计算它在序列中的位置,将它归一化到 -1 到 1 的范围内并放到 `normalized_beat_2d` 的第二列。最终得到的 `normalized_beat_2d` 就是所需的形式。
相关问题
normalized_beat_2d[i] = np.zeros((len(normalized_beat[i]),), dtype=object) normalized_beat_2d[i] = np.zeros((len(normalized_beat[i]), 2)) normalized_beat_2d[i][:, 0] = normalized_beat[i] normalized_beat_2d[i][:, 1] = (i / 255) mtf = MarkovTransitionField() image[i] = mtf.transform(normalized_beat_2d[i])之后怎么保存马尔可夫变化生成的图像
你可以使用Python中的PIL库或OpenCV库将生成的图像保存为图像文件,比如PNG、JPEG等格式。下面是使用PIL库保存图像的示例代码:
```python
from PIL import Image
# 假设生成的图像为image[i]
# 将图像转换为PIL Image对象
pil_image = Image.fromarray(image[i])
# 保存图像到文件
pil_image.save('output.png')
```
你也可以使用OpenCV库保存图像,示例代码如下:
```python
import cv2
# 假设生成的图像为image[i]
# 保存图像到文件
cv2.imwrite('output.png', image[i])
```
注意,保存图像时需要指定文件名和文件格式。如果文件名后缀和实际保存的图像格式不一致,可能会导致无法正常打开图像文件。
normalized_beat_2d[i] = np.zeros((len(normalized_beat[i]), 2)) normalized_beat_2d[i, 0] = normalized_beat[i] normalized_beat_2d[i, 1] = (i / (len(normalized_beat[i]) - 1)) * 2 - 1 mtf = MarkovTransitionField() image[i] = mtf.transform(normalized_beat_2d[i]) print('normalized_beat_2d[{}] ='.format(i), normalized_beat_2d[i]) print('len(normalized_beat_2d[{}]) ='.format(i), len(normalized_beat_2d[i]))报错Traceback (most recent call last): File "D:\pythonProject_ecg_analyzation\main.py", line 22, in <module> GetBeats.getbeats(r_peaks, ecg_voltage, user_number) File "D:\pythonProject_ecg_analyzation\GetBeats.py", line 53, in getbeats normalized_beat_2d[i, 0] = normalized_beat[i] TypeError: list indices must be integers or slices, not tuple怎么改
这个错误是因为 `normalized_beat_2d` 是一个列表,而在赋值时使用了类似于数组的方式进行索引。需要将 `normalized_beat_2d` 改为一个 NumPy 数组,代码如下:
```
normalized_beat_2d = np.zeros((len(normalized_beat),), dtype=object)
for i in range(len(normalized_beat)):
normalized_beat_2d[i] = np.zeros((len(normalized_beat[i]), 2))
normalized_beat_2d[i][:, 0] = normalized_beat[i]
normalized_beat_2d[i][:, 1] = (i / (len(normalized_beat[i]) - 1)) * 2 - 1
mtf = MarkovTransitionField()
image[i] = mtf.transform(normalized_beat_2d[i])
print('normalized_beat_2d[{}] ='.format(i), normalized_beat_2d[i])
print('len(normalized_beat_2d[{}]) ='.format(i), len(normalized_beat_2d[i]))
```
这里使用了一个大小为 `len(normalized_beat)` 的对象数组 `normalized_beat_2d`,然后在遍历 `normalized_beat` 的过程中,为每个元素赋值一个大小为 `(len(normalized_beat[i]), 2)` 的 NumPy 数组。对这个 NumPy 数组进行赋值时,可以使用 `[:, 0]` 和 `[:, 1]` 分别取出第一列和第二列的值。
阅读全文