天天看點

在矩形内随機生成不相交的相同圓形

使用python和opencv在矩形内随機生成不相交的相同圓形

import cv2
import numpy as np

# 生成随機圓
class Random_circle(object):
    def __init__(self,minnum,maxnum,height,width,radius):
        self.circle = np.random.randint(minnum,maxnum) #生成随機圓形個數
        self.h = height  #圖像高
        self.w = width  #圖像寬
        self.radius = radius  #圓的半徑
        self.circle_pos = []  #存儲圓心坐标
        self.img = self.create_img()  #生成圖像
    
    #檢測随機生成的圓心與之前生成的圓心距離
    def radius_detect(self,x,y):  
        if(self.circle_pos):  #排除第一個無法比較的圓心
            for pos in self.circle_pos:  #列舉所有之前生成的圓心坐标
                if(((pos[0]-x)**2+(pos[1]-y)**2)**0.5>=self.radius*2): #比較兩點距離與半徑*2的大小
                    continue #若大于等于,則繼續比較
                else:
                    return 1 #若小于,則繼續循環生成随機圓心坐标
                return 0 #列舉結束,跳出循環
        else:
            return 0 
    
    def create_img(self):
        background = np.ones((self.h,self.w),np.uint8) #生成黑色背景
        for num in range(0,self.circle):
            x = np.random.randint(self.radius,self.w-self.radius) #防止圓形跑到邊界外
            y = np.random.randint(self.radius,self.h-self.radius)
            while(self.radius_detect(x,y)): #比較是否重合
                x = np.random.randint(self.radius,self.w-self.radius)
                y = np.random.randint(self.radius,self.h-self.radius)  
            self.circle_pos.append((x,y)) #将不重合的圓添加到圓心坐标中
            img = cv2.circle(background,(x,y),self.radius,(255,255,255),-1) #描繪所有圓       
        return img
    

if __name__ == "__main__":
    #随機生成10-50個圓,圖像高600,寬900,圓的半徑20
    rand = Random_circle(minnum=10,maxnum=50,height=600,width=900,radius=20) 
    circle = rand.circle #讀取圓的個數
    img = rand.img #讀取圖像
    
    print(circle) #列印個數
    cv2.imshow("circle",img) #顯示圖像
    cv2.waitKey(0)
    cv2.destroyAllWindows()
           

結果如下圖

在矩形内随機生成不相交的相同圓形