目錄
1.在區間[a,b)隨機生成n個整數。
2.在區間[a,b)隨機生成n個數。
3.在區間[0,1)生成隨機數
4.打亂順序
5.從指定的列表中選擇
NumPy(Numerical Python)是一個開源的科學計算庫,專門用于高效處理多維數組(ndarray)和數值運算。它是 Python 生態中數據科學、機器學習、工程計算等領域的核心工具之一,提供了比原生 Python 列表更高效、更便捷的數組操作能力。
在 NumPy 中,numpy.random
?是一個子模塊,專門用于生成偽隨機數(即基于算法生成的、看似隨機但可復現的數值序列)。它提供了豐富的函數,可以生成不同分布的隨機數(如均勻分布、正態分布、泊松分布等),并支持隨機數組的生成、隨機采樣、打亂數據等操作。
1.在區間[a,b)隨機生成n個整數。
np.random.randint
import numpy as np
x = np.random.randint(5, 10, 1)#在[5,10)中隨機生成1個整數
y = np.random.randint(3, 15, 4)#在[3,15)中隨機生成4個整數
print(x)
print(y)
print(type(x))
print(type(x))
z = np.random.randint(5, 10)#在[5,10)中隨機生成1個整數
print(z)
print(type(z))
輸出
[8]
[12 ?7 12 ?9]
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
6
<class 'int'>
可以看到隨機數是numpy數組的格式<class 'numpy.ndarray'>
===========================補充==============================
opencv 讀取的圖片,本質上也是numpy 數組的形式。
對于一個彩色圖像RGB來說,是一個三維的數組。
通過.flatten()可分離為3個一維的數組。
import numpy as np
import cv2#圖片變數組
img = cv2.imread("MN.png")
print(type(img))
print(img.shape)
height, width = img.shape[:2]# 提取三個通道并展平為一維數組
lst1 = img[:, :, 0].flatten() # Blue 通道
lst2 = img[:, :, 1].flatten() # Green 通道
lst3 = img[:, :, 2].flatten() # Red 通道print("Blue 通道 (lst1):", len(lst1))
print("Green 通道 (lst2):", len(lst2))
print("Red 通道 (lst3):", len(lst3))
輸出:
<class 'numpy.ndarray'>
(387, 688, 3)
Blue 通道 (lst1): 266256
Green 通道 (lst2): 266256
Red 通道 (lst3): 266256
當然,數組也能反過來變成圖片。
通過np.random.randint隨機生成3個數組,三合1,變成一張彩色圖像。
import numpy as np
import cv2#圖片變數組
img = cv2.imread("MN.png")
print(type(img))
print(img.shape)
height, width = img.shape[:2]# 提取三個通道并展平為一維數組
lst1 = img[:, :, 0].flatten() # Blue 通道
lst2 = img[:, :, 1].flatten() # Green 通道
lst3 = img[:, :, 2].flatten() # Red 通道print("Blue 通道 (lst1):", len(lst1))
print("Green 通道 (lst2):", len(lst2))
print("Red 通道 (lst3):", len(lst3))#數組變圖片
lst4 = np.random.randint(0,256,266256).astype(np.uint8)
lst5 = np.random.randint(0,256,266256).astype(np.uint8)
lst6 = np.random.randint(0,256,266256).astype(np.uint8)
print(lst4.dtype)
blue = lst4.reshape((height, width))
green = lst5.reshape((height, width))
red = lst6.reshape((height, width))
new_img = cv2.merge([blue, green, red])cv2.imshow("Modified Image", new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:
lst4 = np.random.randint(0,256,266256).astype(np.uint8)
np.random.randint中的元素是int32格式,要改為opencv所用的np.uint8格式。
運行后,得到雜亂無章的雪花圖。
=================補充的補充======================
當你有很多張yellow圖,但無法通過審核來發送給你的好兄弟時。
是否可以通過這種方法(圖像轉數組,存入txt,發送。收到后在轉圖像),來實現呢?
代碼中的MN.png(尺寸:(387, 688, 3)):
圖片轉數組并存入txt,代碼如下:
import numpy as np
import cv2#圖片變數組
img = cv2.imread("MN.png")
print(img.shape)
height, width = img.shape[:2]# 提取三個通道并展平為一維數組
lst1 = img[:, :, 0].flatten() # Blue 通道
lst2 = img[:, :, 1].flatten() # Green 通道
lst3 = img[:, :, 2].flatten() # Red 通道# 保存到txt文件(每個通道占一行,空格分隔)
combined = np.array([lst1, lst2, lst3])
np.savetxt("img_data.txt", combined, fmt="%d")
txt中提取數組,并數組轉圖片,代碼如下:
import numpy as np
import cv2
height= 387
width = 688# 讀取文件內容
data = np.loadtxt("img_data.txt", dtype=int)
# 提取三個通道
blue = data[0].reshape(height, width).astype(np.uint8)
green = data[1].reshape(height, width).astype(np.uint8)
red = data[2].reshape(height, width).astype(np.uint8)
new_img = cv2.merge([blue, green, red])cv2.imshow("Modified Image", new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img_data.txt:
(為什么圖片轉數組后,txt比圖片大這么多。。。)
運行后:非常清晰
完整代碼:
里面放了很多 比較得勁的 img_data.txt ,自己轉了看把? =-=。
通過網盤分享的文件:test_np_cv
鏈接: https://pan.baidu.com/s/1y9YDJWw9xvG6AakM5X4GUA
提取碼: ebtg
==============================================================
2.在區間[a,b)隨機生成n個數。
np.random.uniform
import numpy as np
x = np.random.uniform(5, 10, 1)#在[5,10)中隨機生成1個數
y = np.random.uniform(3, 15, 4)#在[3,15)中隨機生成4個數
print(x)
print(y)
print(type(x))
print(type(x))
z = np.random.uniform(5, 10)#在[5,10)中隨機生成1個數
print(z)
print(type(z))
3.在區間[0,1)生成隨機數
rand 與 randn
import numpy as np# 平均數
def average(lst):sum_lst = 0for n in lst:sum_lst = sum_lst+nreturn sum_lst/len(lst)X = np.random.rand(100)#隨機生成100個數
Y = np.random.randn(100)#隨機生成100個數print(average(X))
print(average(Y))
運行多次后發現,
average(X) = 0.5
average(Y) = 0
rand是[0, 1)
?均勻分布隨機數
randn標準正態分布隨機數,范圍是?(-∞, +∞),但大部分值落在?[-3, +3]?之間。
rand 與 randn可用于模擬數據,例如:y = 3x + 4 ,x在[0,3)上的近似數據。
import numpy as np
import matplotlib.pyplot as plt
# 平均數
def average(lst):sum_lst = 0for n in lst:sum_lst = sum_lst+nreturn sum_lst/len(lst)# 生成特征數據 X:100個 [0,3) 區間的均勻分布隨機數
x = 3 * np.random.rand(100) # np.random.rand生成[0,1)均勻分布,乘以3擴展到[0,3)# 生成目標數據 y:線性關系 y = 4 + 3X + 高斯噪聲
y = 4 + 3 * x + np.random.randn(100) # np.random.randn生成標準正態分布噪聲# 可視化原始數據
plt.plot(x, y, 'b.') # 藍色點圖
plt.xlabel('x1') # x軸標簽
plt.ylabel('y') # y軸標簽
plt.axis([0, 3, 0, 20]) # 設置坐標范圍:x[0,3], y[0,20]
plt.show()
運行后:
4.打亂順序
shuffle
import numpy as np
lst = [ 1,2,3,4,5,6]
np.random.shuffle(lst)#打亂數組
print(lst)
輸出[4, 2, 1, 5, 6, 3]
====================
在第一節的補充的補充中,數組轉圖片中
打亂一維的數組后,
產生了噪音:
代碼:
import numpy as np
import cv2
height= 387
width = 688# 讀取文件內容
data = np.loadtxt("img_data.txt", dtype=int)
# 提取三個通道
blue = data[0].reshape(height, width).astype(np.uint8)
green = data[1].reshape(height, width).astype(np.uint8)
red = data[2].reshape(height, width).astype(np.uint8)
np.random.shuffle(blue)
new_img = cv2.merge([blue, green, red])cv2.imshow("Modified Image", new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
5.從指定的列表中選擇
np.random.choice
import numpy as nplst1 = [1,2,3,5,8,9,15,21]
print(np.random.choice(lst1))lst2 = ["一等獎","二等獎","三等獎","謝謝惠顧"]
print(np.random.choice(lst2))
修改各個選項的概率:
import numpy as np
lst2 = ["一等獎","二等獎","三等獎","謝謝惠顧"]
lst2_weight = [0.1, 0.2, 0.3,0.4]
result = np.random.choice(lst2, p=lst2_weight)
print(result)
概率為0.1,0.2,0.3,0.4
動態概率:模擬原神抽卡
lst = ['綠', '班尼特','芭芭拉','七七','刻晴','鐘離']
lst_probabilities = [90 / 100, 4.5 / 100, 4.5 / 100, 0.3 / 100, 0.3 / 100, 0.4 / 100]
不斷抽獎中,隨著count的增加
count += 1
lst_probabilities跟著改變
lst_probabilities = [90 / 100-6*int(count2)/1000, 4.5 / 100, 4.5 / 100, 0.3 / 100+2*int(count2)/1000, 0.3 / 100+2*int(count2)/1000, 0.4 / 100+2*int(count2)/1000]
運行后:
完整代碼
?
import sys
import numpy as np
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,QHBoxLayout, QLineEdit, QPushButton)
from PyQt5.QtCore import Qtclass GachaApp(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle('非酋or歐皇')self.setFixedSize(800, 400)self.count = 0self.count2 = 0self.lst = ['綠', '班尼特', '芭芭拉', '七七', '刻晴', '鐘離']self.lst_probabilities = [90 / 100, 4.5 / 100, 4.5 / 100, 0.3 / 100, 0.3 / 100, 0.4 / 100]self.initUI()def initUI(self):central_widget = QWidget()self.setCentralWidget(central_widget)main_layout = QVBoxLayout()central_widget.setLayout(main_layout)# 輸入框網格self.input_boxes = []grid_layout = QHBoxLayout()for i in range(10):input_box = QLineEdit()input_box.setAlignment(Qt.AlignCenter)input_box.setFixedSize(60, 60)input_box.setReadOnly(True)self.input_boxes.append(input_box)grid_layout.addWidget(input_box)main_layout.addLayout(grid_layout)# 抽卡按鈕self.gacha_btn = QPushButton('抽卡')self.gacha_btn.setFixedSize(150, 50)self.gacha_btn.clicked.connect(self.gacha)# 計數器self.count_btn = QPushButton("0")self.count_btn.setFixedSize(80, 30)self.count_btn.setEnabled(False)# 重新開始按鈕self.reset_btn = QPushButton('重新開始')self.reset_btn.setFixedSize(100, 30)self.reset_btn.clicked.connect(self.reset)# 按鈕布局btn_layout = QHBoxLayout()btn_layout.addWidget(self.gacha_btn)btn_layout.addWidget(self.count_btn)btn_layout.addWidget(self.reset_btn)main_layout.addLayout(btn_layout)def gacha(self):self.count += 1self.count_btn.setText(f"{self.count}")# 更新概率(根據你的原始邏輯)self.lst_probabilities = [90 / 100 - 3 * self.count2 / 1000,4.5 / 100,4.5 / 100,0.3 / 100 + 1 * self.count2 / 1000,0.3 / 100 + 1 * self.count2 / 1000,0.4 / 100 + 1 * self.count2 / 1000]# 歸一化處理(確保概率總和為1)prob_sum = sum(self.lst_probabilities)self.lst_probabilities = [p / prob_sum for p in self.lst_probabilities]# 抽卡并顯示結果for i in range(10):result = np.random.choice(self.lst, p=self.lst_probabilities)self.input_boxes[i].setText(result)if result in ['七七', '鐘離', '刻晴']:self.show_popup(f"恭喜你 抽到了 {result}")self.count2 = 0else:self.count2 += 1def reset(self):self.count = 0self.count2 = 0self.count_btn.setText(f"{self.count}")for box in self.input_boxes:box.clear()def show_popup(self, message):from PyQt5.QtWidgets import QMessageBoxmsg = QMessageBox()msg.setIcon(QMessageBox.Information)msg.setText(message)msg.setWindowTitle("恭喜")msg.setStandardButtons(QMessageBox.Ok)msg.exec_()if __name__ == '__main__':app = QApplication(sys.argv)ex = GachaApp()ex.show()sys.exit(app.exec_())