GVKun编程网logo

Python numpy 模块-int0() 实例源码(python中numpy模块)

3

如果您对Pythonnumpy模块-int0()实例源码感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Pythonnumpy模块-int0()实例源码的详细内容,我们还将为

如果您对Python numpy 模块-int0() 实例源码感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Python numpy 模块-int0() 实例源码的详细内容,我们还将为您解答python中numpy模块的相关问题,并且为您提供关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的有价值信息。

本文目录一览:

Python numpy 模块-int0() 实例源码(python中numpy模块)

Python numpy 模块-int0() 实例源码(python中numpy模块)

Python numpy 模块,int0() 实例源码

我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用numpy.int0()

项目:dust_repos    作者:taozhijiang    | 项目源码 | 文件源码
  1. def img_contour_select(ctrs, im):
  2. # ????????????
  3. cand_rect = []
  4. for item in ctrs:
  5. epsilon = 0.02*cv2.arcLength(item, True)
  6. approx = cv2.approxpolyDP(item, epsilon, True)
  7. if len(approx) <= 8:
  8. rect = cv2.minAreaRect(item)
  9. if rect[1][0] < 20 or rect[1][1] < 20:
  10. continue
  11. if rect[1][0] > 150 or rect[1][1] > 150:
  12. continue
  13. #ratio = (rect[1][1]+0.00001) / rect[1][0]
  14. #if ratio > 1 or ratio < 0.9:
  15. # continue
  16. Box = cv2.BoxPoints(rect)
  17. Box_d = np.int0(Box)
  18. cv2.drawContours(im, [Box_d], 0, (0,255,0), 3)
  19. cand_rect.append(Box)
  20. img_show_hook("????", im)
  21. return cand_rect
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
  1. def draw_markers(img,markers):
  2. for m in markers:
  3. centroid = np.array(m[''centroid''],dtype=np.float32)
  4. origin = np.array(m[''verts''][0],dtype=np.float32)
  5. hat = np.array([[[0,0],[0,1],[.5,1.25],[1,0]]],dtype=np.float32)
  6. hat = cv2.perspectiveTransform(hat,m_marker_to_screen(m))
  7. if m[''id_confidence'']>.9:
  8. cv2.polylines(img,np.int0(hat),color = (0,0,255),isClosed=True)
  9. else:
  10. cv2.polylines(img,isClosed=True)
  11. # cv2.polylines(img,np.int0(centroid),color = (255,255,int(255*m[''id_confidence''])),isClosed=True,thickness=2)
  12. m_str = ''id: {:d}''.format(m[''id''])
  13. org = origin.copy()
  14. # cv2.rectangle(img,tuple(np.int0(org+(-5,-13))[0,:]),tuple(np.int0(org+(100,30))[0,color=(0,0),thickness=-1)
  15. cv2.putText(img,m_str,tuple(np.int0(org)[0,fontFace=cv2.FONT_HERShey_SIMPLEX, fontScale=0.4, color=(0,255))
  16. if ''id_confidence'' in m:
  17. m_str = ''idc: {:.3f}''.format(m[''id_confidence''])
  18. org += (0, 12)
  19. cv2.putText(img,255))
  20. if ''loc_confidence'' in m:
  21. m_str = ''locc: {:.3f}''.format(m[''loc_confidence''])
  22. org += (0, 12 )
  23. cv2.putText(img,255))
  24. if ''frames_since_true_detection'' in m:
  25. m_str = ''otf: {}''.format(m[''frames_since_true_detection''])
  26. org += (0,255))
  27. if ''opf_vel'' in m:
  28. m_str = ''otf: {}''.format(m[''opf_vel''])
  29. org += (0,255))
项目:dust_repos    作者:taozhijiang    | 项目源码 | 文件源码
  1. def img_contour_select(ctrs, True)
  2. if len(approx) <= 8:
  3. rect = cv2.minAreaRect(item)
  4. #????????
  5. if rect[2] < -10 and rect[2] > -80:
  6. continue
  7. if rect[1][0] < 10 or rect[1][1] < 10:
  8. continue
  9. #ratio = (rect[1][1]+0.00001) / rect[1][0]
  10. #if ratio > 1 or ratio < 0.9:
  11. # continue
  12. Box = cv2.BoxPoints(rect)
  13. Box_d = np.int0(Box)
  14. cv2.drawContours(im, im)
  15. return cand_rect
项目:idmatch    作者:maddevsio    | 项目源码 | 文件源码
  1. def remove_border(contour, ary):
  2. """Remove everything outside a border contour."""
  3. # Use a rotated rectangle (should be a good approximation of a border).
  4. # If it''s far from a right angle,it''s probably two sides of a border and
  5. # we should use the bounding Box instead.
  6. c_im = np.zeros(ary.shape)
  7. r = cv2.minAreaRect(contour)
  8. degs = r[2]
  9. if angle_from_right(degs) <= 10.0:
  10. Box = cv2.BoxPoints(r)
  11. Box = np.int0(Box)
  12. cv2.drawContours(c_im, [Box], 255, -1)
  13. cv2.drawContours(c_im, 4)
  14. else:
  15. x1, y1, x2, y2 = cv2.boundingRect(contour)
  16. cv2.rectangle(c_im, (x1, y1), (x2, y2), -1)
  17. cv2.rectangle(c_im, 4)
  18.  
  19. return np.minimum(c_im, ary)
项目:dataArtist    作者:radjkarl    | 项目源码 | 文件源码
  1. def getMask(self, shape):
  2.  
  3. p=self.state[''pos'']
  4. s=self.state[''size'']
  5. center=p + s / 2
  6. a=self.state[''angle'']
  7. # opencv convention:
  8. shape = (shape[1], shape[0])
  9. arr1 = np.zeros(shape, dtype=np.uint8)
  10. arr2 = np.zeros(shape, dtype=np.uint8)
  11.  
  12. # draw rotated rectangle:
  13. vertices = np.int0(cv2.BoxPoints((center, s, a)))
  14. cv2.drawContours(arr1, [vertices], color=1, thickness=-1)
  15. # draw ellipse:
  16. cv2.ellipse(arr2, (int(center[0]), int(center[1])), (int(s[0] / 2 * self._ratioEllispeRectangle),
  17. int(s[1] / 2 * self._ratioEllispeRectangle)), int(a),
  18. startAngle=0, endAngle=360, thickness=-1)
  19. # bring both together:
  20. return np.logical_and(arr1, arr2).T
项目:dataArtist    作者:radjkarl    | 项目源码 | 文件源码
  1. def getMask(self, shape):
  2.  
  3. p = self.state[''pos'']
  4. s = self.state[''size'']
  5. center = p + s / 2
  6. a = self.state[''angle'']
  7. # opencv convention:
  8. shape = (shape[1], shape[0])
  9. arr = np.zeros(shape, dtype=np.uint8)
  10. # draw rotated rectangle:
  11. vertices = np.int0(cv2.BoxPoints((center, a)))
  12. cv2.drawContours(arr,
  13. 0,
  14. color=1,
  15. thickness=-1)
  16. return arr.astype(bool).T
项目:Recognition    作者:thautwarm    | 项目源码 | 文件源码
  1. def deal(self,frame):
  2. frame=frame.copy()
  3. track_window=self.track_window
  4. term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
  5. roi_hist=self.roi_hist
  6. dst = cv2.calcBackProject([frame],[0],roi_hist,180],1)
  7. if self.m==''m'':
  8. ret, track_window_r = cv2.meanShift(dst, track_window, term_crit)
  9. x,y,w,h = track_window_r
  10. img2 = cv2.rectangle(frame, (x,y), (x+w,y+h),2)
  11. elif self.m==''c'':
  12. ret, track_window_r = cv2.CamShift(dst, term_crit)
  13.  
  14.  
  15. pts = cv2.BoxPoints(ret)
  16. pts = np.int0(pts)
  17. img2 = cv2.polylines(frame,[pts],True,2)
  18. rectsNew=[]
  19.  
  20. center1=(track_window[0]+track_window[2]//2,track_window[1]+track_window[3]//2)
  21. center2=(track_window_r[0]+track_window_r[2]//2,track_window_r[1]+track_window_r[3]//2)
  22. img2 = cv2.line(img2,center1,center2,color=0)
  23. rectsNew=track_window_r
  24. # x,y,w,h = track_window
  25. # img2 = cv2.rectangle(frame,(x,y),(x+w,y+h),2)
  26. cv2.imshow(''img2'',img2)
  27. cv2.waitKey(0)
  28. cv2.destroyAllWindows()
  29. return rectsNew
项目:PAN-Card-OCR    作者:dilippuri    | 项目源码 | 文件源码
  1. def remove_border(contour,it''s probably two sides of a border and
  2. # we should use the bounding Box instead.
  3. c_im = np.zeros(ary.shape)
  4. r = cv2.minAreaRect(contour)
  5. degs = r[2]
  6. if angle_from_right(degs) <= 10.0:
  7. Box = cv2.cv.BoxPoints(r)
  8. Box = np.int0(Box)
  9. cv2.drawContours(c_im, ary)
项目:unmixing    作者:arthur-e    | 项目源码 | 文件源码
  1. def density_slice(rast, rel=np.less_equal, threshold=1000, nodata=-9999):
  2. ''''''
  3. Returns a density slice from a given raster. Arguments:
  4. rast A gdal.Dataset or a NumPy array
  5. rel A NumPy logic function; defaults to np.less_equal
  6. threshold An integer number
  7. ''''''
  8. # Can accept either a gdal.Dataset or numpy.array instance
  9. if not isinstance(rast, np.ndarray):
  10. rastr = rast.ReadAsArray()
  11.  
  12. else:
  13. rastr = rast.copy()
  14.  
  15. if (len(rastr.shape) > 2 and min(rastr.shape) > 1):
  16. raise ValueError(''Expected a single-band raster array'')
  17.  
  18. return np.logical_and(
  19. rel(rastr, np.ones(rast.shape) * threshold),
  20. np.not_equal(rastr, np.ones(rast.shape) * nodata)).astype(np.int0)
项目:Millennium-Eye    作者:Elysium1937    | 项目源码 | 文件源码
  1. def shapeFiltering(img):
  2. contours = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
  3. if len(contours) == 0:
  4. return "yoopsie"
  5. #else:
  6. #print contours
  7. """blank_image = np.zeros((img.shape[0],img.shape[1],3),np.uint8)
  8. cv2.drawContours(blank_image,contours,-1,(255,255))
  9. cv2.imshow("imagiae",blank_image)
  10. cv2.waitKey()"""
  11. good_shape = []
  12. for c in contours:
  13. x,h = cv2.boundingRect(c)
  14. """rect = cv2.minAreaRect(contour)
  15. Box = cv2.BoxPoints(rect)
  16. Box = np.int0(Box)
  17. w = """
  18. #if h == 0:
  19. # continue
  20. ratio = w / h
  21. ratio_grade = ratio / (TMw / TMh)
  22. if 0.2 < ratio_grade < 1.8:
  23. good_shape.append(c)
  24. """blank_image = np.zeros((img.shape[0],good_shape,255))
  25. cv2.imshow("imagia",blank_image)
  26. cv2.waitKey()"""
  27. return good_shape
项目:Millennium-Eye    作者:Elysium1937    | 项目源码 | 文件源码
  1. def findCorners(contour):
  2. """blank_image = np.zeros((img.shape[0],contour,255))
  3. rows,cols = img.shape[0],img.shape[1]
  4. M = cv2.getRotationMatrix2D((cols/2,rows/2),-45,0.5)
  5. dst = cv2.warpAffine(blank_image,M,(cols,rows))
  6. cv2.imshow("rotatio",dst)
  7. cv2.waitKey()"""
  8. rect = cv2.minAreaRect(contour)
  9. Box = cv2.BoxPoints(rect)
  10. Box = np.int0(Box)
  11. height_px_1 = Box[0][1] - Box[3][1]
  12. height_px_2 = Box[1][1] - Box[2][1]
  13. print height_px_1, height_px_2
  14. if height_px_1 < height_px_2:
  15. close_height_px = height_px_2
  16. far_height_px = height_px_1
  17. else:
  18. close_height_px = height_px_1
  19. far_height_px = height_px_2
  20.  
  21. return close_height_px, far_height_px
项目:Millennium-Eye    作者:Elysium1937    | 项目源码 | 文件源码
  1. def findCorners(contour):
  2. rect = cv2.minAreaRect(contour)
  3. Box = cv2.BoxPoints(rect)
  4. Box = numpy.int0(Box)
  5. height_px_1 = Box[0][1] - Box[3][1]
  6. height_px_2 = Box[1][1] - Box[2][1]
  7. print height_px_1, far_height_px
项目:dataArtist    作者:radjkarl    | 项目源码 | 文件源码
  1. def update(roi):
  2. img1b.setimage(roi.getArrayRegion(arr, img1a), levels=(0, arr.max()))
  3. img1c.setimage(np.int0(r.getMask(arr.shape)))
  4.  
  5. # cell.sigRegionChanged.connect(update)
  6. # update(cell)
项目:omr    作者:rbaron    | 项目源码 | 文件源码
  1. def get_bounding_rect(contour):
  2. rect = cv2.minAreaRect(contour)
  3. Box = cv2.BoxPoints(rect)
  4. return np.int0(Box)
项目:Smart-Car    作者:jimchenhub    | 项目源码 | 文件源码
  1. def shi_tomasi(gray):
  2. # image????
  3. # maxCorners???????
  4. # qualityLevel?????????????????????
  5. # mindistance??????????
  6. corners = cv2.goodFeaturesToTrack(gray,25,0.01,10)
  7. cv2.computeCorrespondEpilines()
  8. # ?????? [[ 311.,250.]] ????????
  9. corners = np.int0(corners)
  10. return corners
项目:2016-Tegra-OpenCV    作者:HighlandersFRC    | 项目源码 | 文件源码
  1. def calculateFrame(self,cap):
  2. data = self.getDataPoints()
  3. #targetCascade = cv2.CascadeClassifier(cascPath)
  4. frame = cap.read()
  5. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  6. lower_bound = np.array([float(data[''HMIN'']),float(data["SMIN"]),float(data[''VMIN''])])
  7. upper_bound = np.array([float(data[''HMAX'']),float(data["SMAX"]),float(data[''VMAX''])])
  8.  
  9. hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
  10. mask = cv2.inRange(hsv,lower_bound,upper_bound)
  11.  
  12. largest_area = 0
  13. xCenter = -1
  14. yCenter = -1
  15. targetRect = None
  16.  
  17. ret,thresh = cv2.threshold(mask,200,0)
  18. contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  19.  
  20. if len(contours) > 1:
  21. areas = [cv2.contourArea(c) for c in contours]
  22. max_index = np.argmax(areas)
  23. cnt = contours[max_index]
  24. rect = cv2.minAreaRect(cnt)
  25. Box = cv2.cv.BoxPoints(rect)
  26. Box = np.int0(Box)
  27.  
  28. xCenter = (Box[0][0] + Box[1][0] + Box[2][0] + Box[3][0]) /4
  29. yCenter = (Box[0][1] + Box[1][1] + Box[2][1] + Box[3][1]) /4
  30. cv2.drawContours(frame,[Box],(0,2)
  31.  
  32.  
  33. output = {}
  34. distance = 0.0025396523 * yCenter**2 + 0.1000098497 *yCenter + 46.8824851568
  35. theta = math.atan2(xCenter-160, distance)
  36. output_dict = {"xCenter": xCenter, "yCenter": yCenter,"theta": theta, "distance":distance}
  37. output = json.dumps(output_dict)
  38.  
  39.  
  40. return frame ,output , True, mask
项目:unmixing    作者:arthur-e    | 项目源码 | 文件源码
  1. def cfmask(mask, mask_values=(1,2,3,4, nodata=-9999):
  2. ''''''
  3. Returns a binary mask according to the CFMask algorithm results for the
  4. image; mask has True for water,cloud,shadow,and sNow (if any) and False
  5. everywhere else. More information can be found:
  6. https://landsat.usgs.gov/landsat-surface-reflectance-quality-assessment
  7.  
  8. Landsat 4-7 Pre-Collection pixel_qa values to be masked:
  9. mask_values = (1,2,3,4)
  10.  
  11. Landsat 4-7 Collection 1 pixel_qa values to be masked (for "Medium" confidence):
  12. mask_values = (1,68,72,80,112,132,136,144,160,176,224)
  13.  
  14. Landsat 8 Collection 1 pixel_qa values to be masked (for "Medium" confidence):
  15. mask_values = (1,324,328,386,388,392,400,416,432,480,832,836,840,848,864,880,900,904,912,928,944,992,1024)
  16.  
  17. Arguments:
  18. mask A gdal.Dataset or a NumPy array
  19. mask_path The path to an EOS HDF4 CFMask raster
  20. mask_values The values in the mask that correspond to NoData pixels
  21. nodata The NoData value; defaults to -9999.
  22. ''''''
  23. if not isinstance(mask, np.ndarray):
  24. maskr = mask.ReadAsArray()
  25.  
  26. else:
  27. maskr = mask.copy()
  28.  
  29. # Mask according to bit-packing described here:
  30. # https://landsat.usgs.gov/landsat-surface-reflectance-quality-assessment
  31. maskr = np.in1d(maskr.reshape((maskr.shape[0] * maskr.shape[1])), mask_values)\\
  32. .reshape((1, maskr.shape[0], maskr.shape[1])).astype(np.int0)
  33.  
  34. return maskr
项目:Vision2016    作者:AluminatiFRC    | 项目源码 | 文件源码
  1. def getTargetBox(target):
  2. minRect = cv2.minAreaRect(target)
  3. Box = cv2.cv.BoxPoints(minRect)
  4. #Box = np.int0(Box) # convert points to ints
  5. return Box
项目:pyANPD    作者:abdulfatir    | 项目源码 | 文件源码
  1. def validate_contour(contour, img, aspect_ratio_range, area_range):
  2. rect = cv2.minAreaRect(contour)
  3. img_width = img.shape[1]
  4. img_height = img.shape[0]
  5. Box = cv2.BoxPoints(rect)
  6. Box = np.int0(Box)
  7.  
  8. X = rect[0][0]
  9. Y = rect[0][1]
  10. angle = rect[2]
  11. width = rect[1][0]
  12. height = rect[1][1]
  13.  
  14. angle = (angle + 180) if width < height else (angle + 90)
  15.  
  16. output=False
  17.  
  18. if (width > 0 and height > 0) and ((width < img_width/2.0) and (height < img_width/2.0)):
  19. aspect_ratio = float(width)/height if width > height else float(height)/width
  20. if (aspect_ratio >= aspect_ratio_range[0] and aspect_ratio <= aspect_ratio_range[1]):
  21. if((height*width > area_range[0]) and (height*width < area_range[1])):
  22.  
  23. Box_copy = list(Box)
  24. point = Box_copy[0]
  25. del(Box_copy[0])
  26. dists = [((p[0]-point[0])**2 + (p[1]-point[1])**2) for p in Box_copy]
  27. sorted_dists = sorted(dists)
  28. opposite_point = Box_copy[dists.index(sorted_dists[1])]
  29. tmp_angle = 90
  30.  
  31. if abs(point[0]-opposite_point[0]) > 0:
  32. tmp_angle = abs(float(point[1]-opposite_point[1]))/abs(point[0]-opposite_point[0])
  33. tmp_angle = rad_to_deg(math.atan(tmp_angle))
  34.  
  35. if tmp_angle <= 45:
  36. output = True
  37. return output
项目:seglink    作者:dengdan    | 项目源码 | 文件源码
  1. def bBoxes_to_xys(bBoxes, image_shape):
  2. """Convert Seglink bBoxes to xys,i.e.,eight points
  3. The `image_shape` is used to to make sure all points return are valid,within image area
  4. """
  5. if len(bBoxes) == 0:
  6. return []
  7.  
  8. assert np.ndim(bBoxes) == 2 and np.shape(bBoxes)[-1] == 5, ''invalid `bBoxes` param with shape = '' + str(np.shape(bBoxes))
  9.  
  10. h, w = image_shape[0:2]
  11. def get_valid_x(x):
  12. if x < 0:
  13. return 0
  14. if x >= w:
  15. return w - 1
  16. return x
  17.  
  18. def get_valid_y(y):
  19. if y < 0:
  20. return 0
  21. if y >= h:
  22. return h - 1
  23. return y
  24.  
  25. xys = np.zeros((len(bBoxes), 8))
  26. for bBox_idx, bBox in enumerate(bBoxes):
  27. bBox = ((bBox[0], bBox[1]), (bBox[2], bBox[3]), bBox[4])
  28. points = cv2.cv.BoxPoints(bBox)
  29. points = np.int0(points)
  30. for i_xy, y) in enumerate(points):
  31. x = get_valid_x(x)
  32. y = get_valid_y(y)
  33. points[i_xy, :] = [x, y]
  34. points = np.reshape(points, -1)
  35. xys[bBox_idx, :] = points
  36. return xys
项目:brainiak    作者:brainiak    | 项目源码 | 文件源码
  1. def __init__(self, fname=None, include_orth=True, include_pols=True):
  2. if fname is None:
  3. # fname is the name of the file to read in the design matrix
  4. self.design = np.zeros([0, 0])
  5. self.n_col = 0
  6. # number of columns (conditions) in the design matrix
  7. self.column_types = np.ones(0)
  8. self.n_basis = 0
  9. self.n_stim = 0
  10. self.n_orth = 0
  11. self.StimLabels = []
  12. else:
  13. # isAFNI = re.match(r''.+[.](1D|1d|txt)$'',fname)
  14. filename, ext = os.path.splitext(fname)
  15. # We assume all AFNI 1D files have extension of 1D or 1d or txt
  16. if ext in [''.1D'', ''.1d'', ''.txt'']:
  17. self.read_afni(fname=fname)
  18.  
  19. self.include_orth = include_orth
  20. self.include_pols = include_pols
  21. # The two flags above dictates whether columns corresponding to
  22. # baseline drift modeled by polynomial functions of time and
  23. # columns corresponding to other orthogonal signals (usually motion)
  24. # are included in nuisance regressors.
  25. self.cols_task = np.where(self.column_types == 1)[0]
  26. self.design_task = self.design[:, self.cols_task]
  27. if np.ndim(self.design_task) == 1:
  28. self.design_task = self.design_task[:, None]
  29. # part of the design matrix related to task conditions.
  30. self.n_TR = np.size(self.design_task, axis=0)
  31. self.cols_nuisance = np.array([])
  32. if self.include_orth:
  33. self.cols_nuisance = np.int0(
  34. np.sort(np.append(self.cols_nuisance,
  35. np.where(self.column_types == 0)[0])))
  36. if self.include_pols:
  37. self.cols_nuisance = np.int0(
  38. np.sort(np.append(self.cols_nuisance,
  39. np.where(self.column_types == -1)[0])))
  40. if np.size(self.cols_nuisance) > 0:
  41. self.reg_nuisance = self.design[:, self.cols_nuisance]
  42. if np.ndim(self.reg_nuisance) == 1:
  43. self.reg_nuisance = self.reg_nuisance[:, None]
  44. else:
  45. self.reg_nuisance = None
  46. # Nuisance regressors for motion,baseline,etc.
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
  1. def _find_array_button_thing(self):
  2. """ Find the array button on the solar array Box """
  3.  
  4. """ This uses color to determine if we have a choke """
  5. lower = np.array([0, 60], dtype = "uint8")
  6. upper = np.array([20, 20, 255], dtype = "uint8")
  7. mask = cv2.inRange(self.img, lower, upper)
  8.  
  9. blurred = cv2.GaussianBlur(mask, (5, 5), 0)
  10. thresh = cv2.threshold(blurred, 60, cv2.THRESH_BINARY)[1]
  11.  
  12. contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  13. contours = contours[0] if is_cv2() else contours[1]
  14.  
  15. debug_img = None
  16. if self.debug:
  17. debug_img = self.img.copy()
  18.  
  19. button_Box = None
  20. for c in contours:
  21. Box = cv2.boundingRect(c)
  22.  
  23. if button_Box is None:
  24. button_Box = Box
  25. else:
  26. button_Box = self._union_Box(deepcopy(button_Box), Box)
  27.  
  28. if button_Box is None:
  29. return
  30.  
  31. top,bottom,left,right,center = self.find_dimensions(np.int0(np.array(self._bound_to_Boxpoints(button_Box))))
  32. if top is None or left is None or center is None:
  33. return None
  34.  
  35. height = self.find_distance(top, bottom)
  36. width = self.find_distance(left, right)
  37.  
  38. if self.debug:
  39. for c in contours:
  40. cv2.drawContours(debug_img, [c], -1, 0), 2)
  41.  
  42. cv2.circle(debug_img, top, 5, (255, 0))
  43. cv2.circle(debug_img, bottom, left, right, 0))
  44. cv2.rectangle(debug_img, (button_Box[0], button_Box[1]),
  45. (button_Box[0] + button_Box[2], button_Box[1] + button_Box[3]), (128, 128), 2)
  46. #cv2.circle(debug_img,center,5,0))
  47.  
  48. cv2.imshow("button picture", debug_img)
  49. cv2.setMouseCallback("button picture", self.handle_mouse)
  50. cv2.waitKey(0)
  51. cv2.destroyAllWindows()
  52.  
  53. self.array_button = Thing(height, width, center, None)
  54. self.array_button.set_array_button()
  55. self.array_button.computed_center = self.compute_center(left, bottom)
  56. self.things.append(self.array_button)
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
  1. def _find_a_thing(self, c, min_height, max_height, min_width, max_width, max_distance, debug_img=None):
  2. rect = cv2.minAreaRect(c)
  3. Box = cv2.cv.BoxPoints(rect) if is_cv2() else cv2.BoxPoints(rect)
  4.  
  5. top,center = self.find_dimensions(np.int0(np.array(Box)))
  6.  
  7. if top is None or left is None or center is None:
  8. return None
  9.  
  10. vertical = self.find_distance(top, bottom)
  11. horizontal = self.find_distance(left, right)
  12. away = self.find_distance(center, None)
  13.  
  14. if vertical > horizontal:
  15. height = vertical
  16. width = horizontal
  17. flipped = False
  18. else:
  19. height = horizontal
  20. width = vertical
  21. flipped = True
  22.  
  23. if height < min_height or height > max_height:
  24. return None
  25.  
  26. if width < min_width or width > max_height:
  27. return None
  28.  
  29. if away > max_distance:
  30. return None
  31.  
  32. # This page was helpful in understanding angle
  33. # https://namkeenman.wordpress.com/2015/12/18/open-cv-determine-angle-of-rotatedrect-minarearect/
  34. angle = rect[2]
  35. if rect[1][0] < rect[1][1]:
  36. angle -= 90.0
  37.  
  38. if debug_img is not None:
  39. x,h = cv2.boundingRect(c)
  40. cv2.drawContours(debug_img, 2)
  41. cv2.drawContours(debug_img, [np.int0(np.array(Box))], 255), 2)
  42. cv2.rectangle(debug_img,(x,(x+w,(255,2)
  43.  
  44. cv2.circle(debug_img, 0))
  45.  
  46.  
  47. return Thing(height, angle)
项目:Stronghold-2016-Vision    作者:team4099    | 项目源码 | 文件源码
  1. def get_contours(orig_image):
  2. """
  3. Get edge points (hopefully corners) from the given opencv image (called
  4. contours in opencv)
  5.  
  6. Parameters:
  7. :param: `orig_image` - the thresholded image from which to find contours
  8. """
  9. new_image = numpy.copy(orig_image)
  10. # cv2.imshow("Vision",new_image)
  11. # cv2.waitKey(1000)
  12. new_image, contours, hierarchy = cv2.findContours(new_image,
  13. cv2.RETR_EXTERNAL,
  14. cv2.CHAIN_APPROX_SIMPLE)
  15. # print(len(contours))
  16. # print(len(contours[0]))
  17. # print(len(contours[0][0]))
  18. # print(len(contours[0][0][0]))
  19. largest_contour = 0
  20. most_matching = 0
  21. min_score = 0
  22. max_area = 0
  23. if len(contours) > 1:
  24. print("Length of contours:", len(contours))
  25. max_area = cv2.contourArea(contours[0])
  26. min_score = average_goal_matching(contours[0])
  27. for i in range(1, len(contours)):
  28. # print(contours[i])
  29. current_score = average_goal_matching(contours[i])
  30. current_area = cv2.contourArea(contours[i])
  31. if current_area > max_area:
  32. max_area = current_area
  33. largest_contour = i
  34. if current_score < min_score and current_score != 0 and current_area > 300 and current_area < 1500:
  35. min_score = current_score
  36. most_matching = i
  37. elif len(contours) == 0:
  38. raise GoalNotFoundException("Goal not found!")
  39. if min_score >= 9999999999999999:
  40. raise GoalNotFoundException("Goal not found!")
  41. print("largest_contour:", largest_contour)
  42. print("Area:", max_area)
  43. # print("largest_contour:",largest_contour)
  44. print("Most matching:", most_matching)
  45. print("score:", min_score)
  46. print("Area of most matching:", cv2.contourArea(contours[most_matching]))
  47.  
  48. rect = cv2.minAreaRect(contours[most_matching])
  49. Box = cv2.BoxPoints(rect)
  50. Box = numpy.int0(Box)
  51. # print(Box)
  52. return numpy.array(contours[most_matching]), Box
项目:ChessBot    作者:pakhandi    | 项目源码 | 文件源码
  1. def detectAllVertices(self, testImg):
  2. # Detecting vertices on the newly constructed board
  3. self.gray = cv2.cvtColor(testImg, cv2.COLOR_BGR2GRAY)
  4.  
  5. tempVertices = cv2.goodFeaturesToTrack(self.gray, int(self.FINAL_VERTICES_COUNT), 0.01, 10)
  6. tempVertices = np.int0(tempVertices)
  7.  
  8. newVertices = []
  9.  
  10. for i in tempVertices:
  11. x, y = i.ravel()
  12. newVertices.append((x, y))
  13.  
  14. # Matrix to store coordinates of vertices on the board
  15. self.ALL_VERTICES = [[(0, 0) for x in range(self.FACTOR + 2)] for x in range(self.FACTOR + 2)]
  16.  
  17. # Filling the matrix
  18. self.ALL_VERTICES[0][0] = (self.CORNERS[1])
  19.  
  20. for i in range(0, self.FACTOR):
  21. for j in range(0, self.FACTOR):
  22. predicted_x = self.ALL_VERTICES[i][j][0] + int(
  23. (self.OUTER_VERTICES[2][self.FACTOR - i][0] - self.OUTER_VERTICES[0][i][0]) / 8)
  24. predicted_y = self.ALL_VERTICES[i][j][1] + int(
  25. (self.OUTER_VERTICES[3][self.FACTOR - i][1] - self.OUTER_VERTICES[1][i][1]) / 8)
  26.  
  27. minn_dist = self.INT_MAX
  28.  
  29. for point in newVertices:
  30. this_dist = Geometry.getPointsdistance(point, (predicted_x, self.ALL_VERTICES[i][j][1]))
  31. if this_dist < minn_dist:
  32. self.ALL_VERTICES[i][j + 1] = point
  33. minn_dist = this_dist
  34.  
  35. minn_dist = self.INT_MAX
  36.  
  37. for point in newVertices:
  38. this_dist = Geometry.getPointsdistance(point, (self.ALL_VERTICES[i][j][0], predicted_y))
  39. if this_dist < minn_dist:
  40. self.ALL_VERTICES[i + 1][j] = point;
  41. minn_dist = this_dist
  42.  
  43. self.ALL_VERTICES[self.FACTOR][self.FACTOR] = (self.CORNERS[3])
项目:ROS-Robotics-By-Example    作者:PacktPublishing    | 项目源码 | 文件源码
  1. def image_callback(self, msg):
  2.  
  3. # convert ROS image to OpenCV image
  4. try:
  5. image = self.bridge.imgmsg_to_cv2(msg, desired_encoding=''bgr8'')
  6. except CvBridgeError as e:
  7. print(e)
  8.  
  9. # create hsv image of scene
  10. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  11.  
  12. # find pink objects in the image
  13. lower_pink = numpy.array([139, 240], numpy.uint8)
  14. upper_pink = numpy.array([159, 121, numpy.uint8)
  15. mask = cv2.inRange(hsv, lower_pink, upper_pink)
  16.  
  17. # dilate and erode with kernel size 11x11
  18. cv2.morphologyEx(mask, cv2.MORPH_CLOSE, numpy.ones((11,11)))
  19.  
  20. # find all of the contours in the mask image
  21. contours, heirarchy = cv2.findContours(mask, cv2.CHAIN_APPROX_SIMPLE)
  22. self.contourLength = len(contours)
  23.  
  24. # Check for at least one target found
  25. if self.contourLength < 1:
  26. print "No target found"
  27.  
  28. else: # target found
  29.  
  30. ## Loop through all of the contours,and get their areas
  31. area = [0.0]*len(contours)
  32. for i in range(self.contourLength):
  33. area[i] = cv2.contourArea(contours[i])
  34.  
  35. #### Target #### the largest "pink" object
  36. target_image = contours[area.index(max(area))]
  37.  
  38. # Using moments find the center of the object and draw a red outline around the object
  39. target_m = cv2.moments(target_image)
  40. self.target_u = int(target_m[''m10'']/target_m[''m00''])
  41. self.target_v = int(target_m[''m01'']/target_m[''m00''])
  42. points = cv2.minAreaRect(target_image)
  43. Box = cv2.cv.BoxPoints(points)
  44. Box = numpy.int0(Box)
  45. cv2.drawContours(image, 2)
  46. rospy.loginfo("Center of target is x at %d and y at %d", int(self.target_u), int(self.target_v))
  47.  
  48. self.target_found = True # set flag for depth_callback processing
  49.  
  50. # show image with target outlined with a red rectangle
  51. cv2.imshow ("Target", image)
  52. cv2.waitKey(3)
  53.  
  54. # This callback function handles processing Kinect depth image,looking for the depth value
  55. # at the location of the center of the pink target.
项目:unmixing    作者:arthur-e    | 项目源码 | 文件源码
  1. def binary_mask(rast, mask, nodata=-9999, invert=False):
  2. ''''''
  3. Applies an arbitrary,binary mask (data in [0,1]) where pixels with
  4. a value of 1 are pixels to be masked out. Arguments:
  5. rast A gdal.Dataset or a NumPy array
  6. mask A gdal.Dataset or a NumPy array
  7. nodata The NoData value; defaults to -9999.
  8. invert Invert the mask? (tranpose meaning of 0 and 1); defaults to False.
  9. ''''''
  10. # Can accept either a gdal.Dataset or numpy.array instance
  11. if not isinstance(rast, np.ndarray):
  12. rastr = rast.ReadAsArray()
  13.  
  14. else:
  15. rastr = rast.copy()
  16.  
  17. if not isinstance(mask, np.ndarray):
  18. maskr = mask.ReadAsArray()
  19.  
  20. else:
  21. maskr = mask.copy()
  22.  
  23. if not np.alltrue(np.equal(rastr.shape[-2:], maskr.shape[-2:])):
  24. raise ValueError(''Raster and mask do not have the same shape'')
  25.  
  26. # Convert Boolean arrays to ones and zeros
  27. if maskr.dtype == bool:
  28. maskr = maskr.astype(np.int0)
  29.  
  30. # Transform into a "1-band" array and apply the mask
  31. if maskr.shape != rastr.shape:
  32. maskr = maskr.reshape((1, maskr.shape[-2], maskr.shape[-1]))\\
  33. .repeat(rastr.shape[0], axis=0) # copy the mask across the "bands"
  34.  
  35. # Todo Compare to place(),e.g.,
  36. # np.place(rastr,mask.repeat(rastr.shape[0],axis=0),(nodata,))
  37. # Mask out areas that match the mask (==1)
  38. if invert:
  39. rastr[maskr < 1] = nodata
  40.  
  41. else:
  42. rastr[maskr > 0] = nodata
  43.  
  44. return rastr
项目:2017-Vision    作者:RoboticsTeam4904    | 项目源码 | 文件源码
  1. def filterContoursFancy(contours, image=None):
  2. if len(contours) == 0:
  3. return []
  4.  
  5. numContours = len(contours)
  6. areas = np.array([cv2.contourArea(contour) for contour in contours])
  7.  
  8. boundingRects = [cv2.boundingRect(contour) for contour in contours]
  9. widths, heights, positions = boundingInfo(boundingRects)
  10.  
  11. rotatedRects = [cv2.minAreaRect(contour) for contour in contours]
  12. if config.withOpenCV3:
  13. rotatedBoxes = [np.int0(cv2.BoxPoints(rect)) for rect in rotatedRects]
  14. else:
  15. rotatedBoxes = [np.int0(cv2.cv.BoxPoints(rect)) for rect in rotatedRects]
  16. rotatedAreas = [cv2.contourArea(Box) for Box in rotatedBoxes]
  17.  
  18. sizescores = [size(area)for area in areas]
  19. ratioscores = ratios(widths, heights)
  20. rotationscores = [rotation(rect) for rect in rotatedRects]
  21. rectangularscores = [distTopolygon(contour, poly) for contour,poly in zip(contours, rotatedBoxes)]
  22. areascores = polygonAreaDiff(areas, rotatedAreas)
  23. quadscores = [Quadrify(contour) for contour in contours]
  24.  
  25. rectangularscores = np.divide(rectangularscores, widths)
  26.  
  27. scores = np.array([sizescores, ratioscores, rotationscores, rectangularscores, areascores, quadscores])
  28. contourscores = np.dot(weights, scores)
  29.  
  30. correctInds, incorrectInds = sortedinds(contourscores)
  31. correctContours = np.array(contours)[correctInds]
  32.  
  33. if config.extra_debug:
  34. print "size,ratio,rotation,rectangular,area,quad"
  35. print "Weights:", weights
  36. print "scores: ", contourscores
  37. print np.average(scores, axis=1)
  38. if len(incorrectInds) != 0:
  39. print "AVG,WORST", test(scores, correctInds, incorrectInds)
  40. for i in range(numContours):
  41. print "CONTOUR " + str(i)
  42. print np.multiply(scores[:, i], weights) #newWeights
  43. print contourscores[i]
  44. if image:
  45. img = copy.deepcopy(image)
  46. Printing.drawImage(img, contours[:i] + contours[i+1:], contours[i], False)
  47. Printing.display(img, "contour " + str(i), doResize=True)
  48. cv2.waitKey(0)
  49. cv2.destroyAllWindows()
  50. return correctContours
项目:2017-Vision    作者:RoboticsTeam4904    | 项目源码 | 文件源码
  1. def filterContoursAutocalibrate(contours, incorrectInds = sortedinds(contourscores)
  2. correctContours = np.array(contours)[correctInds]
  3.  
  4. averagescore = 0
  5. for i in range(numContours):
  6. averagescore += sizescores[i]
  7. averagescore += ratioscores[i]
  8. averagescore += rotationscores[i]
  9. averagescore += rectangularscores[i]
  10. averagescore += areascores[i]
  11. averagescore += quadscores[i]
  12. averagescore /= numContours
  13. return averagescore
项目:ROS-Robotics-by-Example    作者:FairchildC    | 项目源码 | 文件源码
  1. def image_callback(self,looking for the depth value
  2. # at the location of the center of the pink target.
项目:indices    作者:shekharshank    | 项目源码 | 文件源码
  1. def detect_barcode(imageval):
  2.  
  3.  
  4. # load the image and convert it to grayscale
  5.  
  6. file_bytes = np.asarray(bytearray(imageval), dtype=np.uint8)
  7. img_data_ndarray = cv2.imdecode(file_bytes, cv2.CV_LOAD_IMAGE_UNCHANGED)
  8. gray = cv2.cvtColor(img_data_ndarray, cv2.COLOR_BGR2GRAY)
  9.  
  10. # compute the Scharr gradient magnitude representation of the images
  11. # in both the x and y direction
  12. gradX = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 1, dy = 0, ksize = -1)
  13. gradY = cv2.Sobel(gray, dx = 0, dy = 1, ksize = -1)
  14.  
  15. # subtract the y-gradient from the x-gradient
  16. gradient = cv2.subtract(gradX, gradY)
  17. gradient = cv2.convertScaleAbs(gradient)
  18.  
  19. # blur and threshold the image
  20. blurred = cv2.blur(gradient, (9, 9))
  21. (_, thresh) = cv2.threshold(blurred, 225, cv2.THRESH_BINARY)
  22.  
  23. # construct a closing kernel and apply it to the thresholded image
  24. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
  25. closed = cv2.morphologyEx(thresh, kernel)
  26.  
  27. # perform a series of erosions and dilations
  28. closed = cv2.erode(closed, None, iterations = 4)
  29. closed = cv2.dilate(closed, iterations = 4)
  30.  
  31. # find the contours in the thresholded image,then sort the contours
  32. # by their area,keeping only the largest one
  33. (cnts, _) = cv2.findContours(closed.copy(),
  34. cv2.CHAIN_APPROX_SIMPLE)
  35. c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
  36.  
  37. # compute the rotated bounding Box of the largest contour
  38. rect = cv2.minAreaRect(c)
  39. Box = np.int0(cv2.cv.BoxPoints(rect))
  40.  
  41. # draw a bounding Box arounded the detected barcode and display the
  42. # image
  43. cv2.drawContours(img_data_ndarray, 3)
  44. # cv2.imshow("Image",image)
  45. #cv2.imwrite("uploads/output-"+ datetime.datetime.Now().strftime("%Y-%m-%d-%H:%M:%s") +".jpg",image)
  46. # cv2.waitKey(0)
  47.  
  48. #outputfile = "uploads/output-" + time.strftime("%H:%M:%s") + ".jpg"
  49. outputfile = "uploads/output.jpg"
  50.  
  51. cv2.imwrite(outputfile,img_data_ndarray)

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel(a, order=''C'')

  Return a flattened array

numpy.chararray.flatten(order=''C'')

  Return a copy of the array collapsed into one dimension

numpy.squeeze(a, axis=None)

  Remove single-dimensional entries from the shape of an array.

 

相同点: 将多维数组 降为 一维数组

不同点:

  ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;

  flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;

  squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;

 

ravel()示例:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 
20 print(a)
21 log_type(''a'',a)

 

flatten()示例

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

squeeze()示例:

1. 没有single-dimensional entries的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。

 

2. 有single-dimentional entries 的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10 
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

一、Numpy数组创建

 part 1:np.linspace(起始值,终止值,元素总个数

 

import numpy as np
''''''
numpy中的ndarray数组
''''''

ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)

''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)

# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)

print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)

# 创建二维数组:
print(np.zeros ((3,4)))

print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)

# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim)  # 返回:3(维)

 

结果图:

 

part 2 :np.linspace ( 起始值,终止值,元素总个数)

 

import numpy as np
a = np.arange( 10, 30, 5 )

b = np.arange( 0, 2, 0.3 )

c = np.arange(12).reshape(4,3)

d = np.random.random((2,3))  # 取-1到1之间的随机数,要求设置为诶2行3列的结构

print(a)
print(b)
print(c)
print(d)

print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))

print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))

 

结果图:

 

 

 

 

二、Numpy的ndarray对象属性:

数组的结构:array.shape

数组的维度:array.ndim

元素的类型:array.dtype

数组元素的个数:array.size

数组的索引(下标):array[0]

 

''''''
数组的基本属性
''''''
import numpy as np

print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)     # 打印数组结构
print(len(a))      # 打印有多少行
print(a.ndim)     # 打印维度
print(a.dtype)    # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size)    # 打印数组的总元素个数


print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)

# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, )  # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)

# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3)   # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )

print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])

print("-----------------")


# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
    for j in range(ary.shape[1]):
        for k in range(ary.shape[2]):
            print(ary[i, j, k], end='' '')
            

 

结果图:

 

关于Python numpy 模块-int0() 实例源码python中numpy模块的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性等相关知识的信息别忘了在本站进行查找喔。

本文标签: