def overlap_img(img1, img2): np.zeros((512, 512)) # Load two images # img1 = cv2.imread('227351.jpg') # 背景 # img2 = cv2.imread('logo.png') # logo # I want to put logo on top-left corner, So I create a ROI rows, cols, channels = img2.shape roi = img1[0:rows, 0:cols] # Now create a mask of logo and create its inverse mask also img2gray = cv2.cv2tColor(img2, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 254, 255, cv2.THRESH_BINARY) # 这个254很重要 mask_inv = cv2.bitwise_not(mask) # cv2.imshow('mask', mask_inv) # Now black-out the area of logo in ROI img1_bg = cv2.bitwise_and(roi, roi, mask=mask) # 这里是mask,我参考的博文写反了,我改正了,费了不小劲 # Take only region of logo from logo image. img2_fg = cv2.bitwise_and(img2, img2, mask=mask_inv) # 这里才是mask_inv # Put logo in ROI and modify the main image dst = cv2.add(img1_bg, img2_fg) img1[0:rows, 0:cols] = dst cv2.imshow('res', img1) cv2.waitKey(0) cv2.destroyAllWindows()
def processImage(fn): print('processing %s... ' % fn) img = cv2.imread(fn, 0) if img is None: print("Failed to load", fn) return None assert w == img.shape[1] and h == img.shape[0], ( "size: %d x %d ... " % (img.shape[1], img.shape[0])) found, corners = cv2.findChessboardCorners(img, pattern_size) if found: term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1) cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term) if debug_dir: vis = cv2.cv2tColor(img, cv2.COLOR_GRAY2BGR) cv2.drawChessboardCorners(vis, pattern_size, corners, found) _path, name, _ext = splitfn(fn) outfile = os.path.join(debug_dir, name + '_chess.png') cv2.imwrite(outfile, vis) if not found: print('chessboard not found') return None print(' %s... OK' % fn) return (corners.reshape(-1, 2), pattern_points)
def get_roi_hist(self, cam_shift): roi = cam_shift[self.r:self.r+self.h, self.c:self.c+self.w] hsv_roi = cv2.cv2tColor(roi, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.))) roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180],[0,180]) cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX) return roi_hist
def process(self, img): # Get region of interest if self.img_num == 0: self.roi_hist = self.get_roi_hist(img) hsv = cv2.cv2tColor(img, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv],[0], self.roi_hist, [0,180], 1) # apply meanshift to get the new location self.ret, self.track_window = cv2.CamShift(dst, self.track_window, self.term_crit) # Increment image counter self.img_num += 1 return self.ret
def Reformat_Image(self, img): # img_dot = cv2.imread("dot.jpg", cv2.IMREAD_COLOR) # gray = cv2.cv2tColor(img_dot, cv2.COLOR_BGR2GRAY) # ret, th1 = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY) # Load the image img = Image.fromarray(cv2.cv2tColor(img, cv2.COLOR_BGR2RGB)) img_w, img_h = img.size background = Image.new('RGB', (200, 200), (255, 255, 255, 255)) bg_w, bg_h = background.size offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2) background.paste(img, offset) # Converting Image to the opencv2 format(BGR) open_cv2_image = np.array(background) # Convert RGB to BGR open_cv2_image = open_cv2_image[:, :, ::-1].copy() if self.no_of_contours(open_cv2_image) == 1: # Getting smallest square contour character cropped_img = self.char_contour(None, open_cv2_image) elif self.no_of_contours(open_cv2_image) > 1: teimg = self.morph(open_cv2_image) cropped_img = self.char_contour(teimg, open_cv2_image) else: cropped_img = self.char_contour(None, open_cv2_image) # Resizing image to 50*50 resolution width = 50 height = 50 dim = (width, height) # resize image if cropped_img is None: return -1 else: resized = cv2.resize(cropped_img, dim, interpolation=cv2.INTER_AREA) return resized
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import sys sys.path.append('/usr/local/include/') import cv2 import numpy as np import math cap = cv2.VideoCapture(0) while(cap.isOpened()): ret, img = cap.read() cv2.rectangle(img,(300,300),(100,100),(0,255,0),0) crop_img = img[100:300, 100:300] grey = cv2.cv2tColor(crop_img, cv2.COLOR_BGR2GRAY) value = (35, 35) blurred = cv2.GaussianBlur(grey, value, 0) _, thresh1 = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) cv2.imshow('Thresholded', thresh1) image, contours, hierarchy = cv2.findContours(thresh1.copy(), \ cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) max_area = -1 for i in range(len(contours)): cnt=contours[i] area = cv2.contourArea(cnt) if(area>max_area): max_area=area ci=i cnt=contours[ci] x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(crop_img,(x,y),(x+w,y+h),(0,0,255),0)
def test(): img = cv2.imread('./test.jpg') newImg = img # 设定窗口 # cv2.namedWindow('Image',cv2.WINDOW_NORMAL) # cv2.imshow('Image',img) # 调用matplotlib画图 plot.imshow(img, cmap='gray', interpolation='bicubic') plot.xticks([]), plot.yticks([]) plot.show() # print(img.shape) # print(img.dtype) width = img.shape[0] height = img.shape[1] # print(width,height) # 添加文字 cv2.putText(newImg, 'hello', (100, 100), cv2.FONT_HERSHEY_COMPLEX, 3, (255, 255, 255), 10) # 等待IO key = cv2.waitKey(0) if key == 27: cv2.destroyAllWindows() elif key == ord('s'): # 保存图像 cv2.imwrite('newtest.png', newImg) print("保存完毕!\n") elif key == ord('m'): # 放大图像 res = cv2.resize(img, (2 * width, 2 * height), interpolation=cv2.INTER_CUBIC) cv2.imwrite('scaleImg.png', res) print("保存完毕!\n") elif key == ord('e'): # 边缘提取 img_gray = cv2.cv2tColor(img, cv2.COLOR_BGR2GRAY) img_gb = cv2.GaussianBlur(img_gray, (5, 5), 0) edges = cv2.Canny(img_gray, 100, 200) cv2.imshow('edge', edges) cv2.imwrite('edges.png', edges) cv2.waitKey(0) cv2.destroyAllWindows() elif key == ord('b'): # 图像信息二值化 th = 100 ret, binary1 = cv2.threshold(img, th, 255, cv2.THRESH_BINARY_INV) ret, binary2 = cv2.threshold(img, th, 255, cv2.THRESH_BINARY) ret, binary3 = cv2.threshold(img, th, 255, cv2.THRESH_TRUNC) ret, binary4 = cv2.threshold(img, th, 255, cv2.THRESH_TOZERO) ret, binary5 = cv2.threshold(img, th, 255, cv2.THRESH_TOZERO_INV) #ret,binary6=cv2.threshold(img,th,255,cv2.THRESH_OTSU) #ret,binary7=cv2.threshold(img,th,255,cv2.THRESH_TRIANGLE) cv2.imshow("THRESH_BINARY_INV", binary1) cv2.imshow("THRESH_BINARY", binary2) cv2.imshow("THRESH_TRUNC", binary3) cv2.imshow("THRESH_TOZERO", binary4) cv2.imshow("THRESH_TOZERO_INV", binary5) #cv2.imshow("THRESH_OTSU",binary6) #cv2.imshow("THRESH_TRIANGLE",binary7) cv2.waitKey(0) cv2.destroyAllWindows()
def load_image(path, gray=True): im = cv2.imread(path) if gray: im = cv2.cv2tColor(im, cv2.COLOR_BGR2RGB) return im
C=2) #%% #%% #Opencv2 notes #Leitura image = cv2.imread("images/obama.jpg") obama = cv2.imread("images/obama.jpg") fraude = load_image("images/fraude_1.jpeg") np_image = np.array(image) image = cv2.cv2tColor(image, cv2.COLOR_BGR2GRAY) # plt.imshow(image) #image = cv2.cv2tColor(image,cv2.COLOR_BGR2RGB) # plt.imshow(image, cmap=cmap, norm=plt.Normalize(vmin=0, vmax=255)) # cv2.waitKey(0) # cv2.imshow('Image',image) #%% #%% #Resize new_image = resizeImage(image, 0.5) # plt.subplot(121) # imshow(image, cmap="gray") # plt.subplot(122) # imshow(new_image, cmap="gray") image = new_image.copy()
def cv2image_to_pygame(image): """Convert cv2image into a pygame image""" image_rgb = cv2.CreateMat(image.height, image.width, cv2.cv2_8UC3) cv2.cv2tColor(image, image_rgb, cv2.cv2_BGR2RGB) return pygame.image.frombuffer(image.tostring(), cv2.GetSize(image_rgb), "RGB")
def cv2image_grayscale(cv2_image): """Converts a cv2image into grayscale""" grayscale = cv2.CreateImage(cv2.GetSize(cv2_image), 8, 1) cv2.cv2tColor(cv2_image, grayscale, cv2.cv2_RGB2GRAY) return grayscale
diff_y = np.subtract(new_y, old_y) diff_x = np.subtract(new_x, old_x) ang = np.arctan2(diff_y, diff_x) * 180 / np.pi mag = np.sqrt(diff_x * diff_x + diff_y * diff_y) return ang, mag ctr = 0 flag = 1 while (count < 250): count += 1 if flag == 1: flag = 0 frameName = 'View3/image' + str(count) + '.jpg' frame = cv2.imread(frameName, 1) frame_gray = cv2.cv2tColor(frame, cv2.COLOR_BGR2GRAY) # calculate optical flow p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params) # Select good points good_new = p1[st == 1] good_old = p0[st == 1] # draw the tracks for i, (new, old) in enumerate(zip(good_new, good_old)): a, b = new.ravel() c, d = old.ravel() #mask = cv2.line(mask, (a,b),(c,d), (0,255,0), 2) frame = cv2.circle(frame, (a, b), 5, (0, 255, 0), -1) #img = cv2.add(frame,mask) #draw_flow(frame_gray, good_new, good_old, step=16) cv2.imshow('frame', frame)
import cv2 src = cv2.imread("./test.png") cv2.namedWindow("input", cv2.WINDOW_AUTOSIZE) cv2.imshow("input", src) gray = cv2.cv2tColor(src, cv2.COLOR_BGR2GRAY) cv2.imwrite('gray.png', gray) cv2.imshow("gray", gray) cv2.waitKey(0) cv2.destroyAllWindows()