python opencv(二) 图像的中基本操作信息

图像中的类操作

import cv2 
import numpy as np 

class File(object):
    def __init__(self,filename) -> None:
        self.filename = filename 
    def open(self,filename=None,mode="r"):
        if filename is None:
            filename = self.filename

        return cv2.imread(filename=filename),open(filename,mode)
    

    
    def save(self,image=None,filename_override=None):
        filename = "output/"+self.filename.split('/')[-1]

        # if filename_override:
        #     filename = "output/"+filename_override
        return  cv2.imwrite(filename,image)
    

class Image(object):
    def __init__(self,image) -> None:
        self.image = image
    def grayscale(self):
        return cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY)
    
    def edges(self):
        return cv2.Canny(self.image,0,255)
    
    def lines(self):
        lines = cv2.HoughLinesP(self.image,1,np.pi/2,6,None,50,10)
        for line in lines[0]:
            pt1 = (line[0],line[1])
            pt2 = (line[2],line[3])

            cv2.line(self.image,pt1,pt2,(0,0,255),2)
        
if __name__ == '__main__':
    file = File('dog.png')
    img = Image(file.open()[0])
    img.image = img.grayscale()
    img.lines()

    file.save(img.image)

图像中的绘制操作

# 绘制矩形操作

cv2.rectangle

cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift )

* 参数表示依次为: (图片,长方形框左上角坐标, 长方形框右下角坐标, 字体颜色,字体粗细)

* 在图片img上画长方形,坐标原点是图片左上角,向右为x轴正方向,向下为y轴正方向。左上角(x,y),右下角(x,y) ,颜色(B,G,R), 线的粗细


import cv2 
import numpy as np
from matplotlib import pyplot as plt

img = np.zeros((400,400,3),dtype = np.uint8)
cv2.imshow("image",img)
cv2.waitKey(0)

# 添加文字操作信息

cv2.putText(img, str(i), (123,456)), font, 2, (0,255,0), 3)

各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细

二维码识别生成和识别操作

import qrcode
import cv2
import numpy as np 



url='https://item.jd.com/7842699.html'
img = qrcode.make(url, border=6)
img.save('macbookPro.jpg')


from pyzbar.pyzbar import decode
# from PIL import Image
import cv2


def main():
    fp = 'macbookPro.jpg'
    # image = Image.open(fp)
    # image.show()
    image = cv2.imread(fp)
    barcodes = decode(image)
    decoded = barcodes[0]
    # #
    url: bytes = decoded.data
    url = url.decode()
    print(url)
    # # rect
    rect = decoded.rect
    print(rect)
    # print(rect)  # Rect(left=19, top=19, width=292, height=292)

    # loop over the detected barcodes
    # for barcode in barcodes:
    # extract the bounding box location of the barcode and draw the
    # bounding box surrounding the barcode on the image
    (x, y, w, h) = decoded.rect
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # the barcode data is a bytes object so if we want to draw it on
    # our output image we need to convert it to a string first
    barcodeData = decoded.data.decode("utf-8")
    barcodeType = decoded.type

    # draw the barcode data and barcode type on the image
    text = "{} ({})".format(barcodeData, barcodeType)
    cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
                0.5, (0, 0, 255), 2)

    # print the barcode type and data to the terminal
    print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))

    # show the output image
    cv2.imshow("Image", image)
    # cv2.imwrite('macbook_qr_rect.jpg', image)
    cv2.waitKey(0)  # 按任意键退出


if __name__ == '__main__':
    main()

图像去除水印


# Import the necessary packages
import cv2
import numpy as np


def back_rm(filename):
    # Load the image
    img = cv2.imread(filename)

    # Convert the image to grayscale
    gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Make a copy of the grayscale image
    bg = gr.copy()

    # Apply morphological transformations
    for i in range(5):
        kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
                                            (2 * i + 1, 2 * i + 1))
        bg = cv2.morphologyEx(bg, cv2.MORPH_CLOSE, kernel2)
        bg = cv2.morphologyEx(bg, cv2.MORPH_OPEN, kernel2)

    # Subtract the grayscale image from its processed copy
    dif = cv2.subtract(bg, gr)

    # Apply thresholding
    bw = cv2.threshold(dif, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    dark = cv2.threshold(bg, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

    # Extract pixels in the dark region
    darkpix = gr[np.where(dark > 0)]

    # Threshold the dark region to get the darker pixels inside it
    darkpix = cv2.threshold(darkpix, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    
    # Paste the extracted darker pixels in the watermark region
    bw[np.where(dark > 0)] = darkpix.T
    
    cv2.imwrite('final.jpg', bw)
back_rm('YZeOg.jpg')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值